改进冒泡排序

Java版本

/*************************************************************************
    > File Name: BubbleSort.java
    > Author: lxm
    > Created Time: 2016年04月27日 星期三 19时24分50秒
 ************************************************************************/

public class BubbleSort
{
    public static final int N = 10;
    public static void main(String[] args)
    {
        int[] a = {6,1,2,7,9,3,4,5,10,8};
        bubbleSort(a);
        printArray(a);
    }

    public static void printArray(int[] a)
    {
        for(int item : a)
        {
            System.out.printf("%d\t",item);
        }
        System.out.println();
    }

    public static void bubbleSort(int[] a)
    {
        int len = a.length;
        boolean flag = true;
        for(int i=0;i<len-1 && flag;++i)
        {
            flag = false;
            for(int j=0;j<len-i-1;++j)
            {
                if(a[j]>a[j+1])
                {
                    swap(a,j,j+1);
                    flag = true;
                }
            }
        }
    }

    public static void swap(int[] a,int m, int n)
    {
        a[m] ^= a[n];
        a[n] ^= a[m];
        a[m] ^= a[n];

    }
}

C版本

/*************************************************************************
    > File Name: bubbleSort.c
    > Author: lxm
    > Created Time: 2016年04月27日 星期三 19时10分36秒
 ************************************************************************/

#include<stdio.h>
#define N 10
void bubbleSort(int* a, int n);
void printArray(int* a, int n);
void swap(int *a,int *b);
int main(void)
{
    int a[] = {6,1,2,7,9,3,4,5,10,8};
    bubbleSort(a,N);
    printArray(a,N);
}
void bubbleSort(int* a, int n)
{
    int i,j;
    int flag = 1;
    for(i=0;flag==1 && i<n-1;i++)
    {
        flag = 0;
        for(j=0;j<n-1-i;++j)
        {
            if(a[j]>a[j+1])
            {
                swap(&a[j],&a[j+1]);
                flag = 1;


            }
        }
    }

}
void printArray(int* a, int n)
{
    int i;
    for(i=0;i<n;++i)
    {
        printf("%d\t",a[i]);
    }
    printf("\n");
}

void swap(int *a,int *b)
{
    *a ^= *b;
    *b ^= *a;
    *a ^= *b;
}
posted @   岳麓丹枫  阅读(113)  评论(0编辑  收藏  举报
编辑推荐:
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
阅读排行:
· 本地部署 DeepSeek:小白也能轻松搞定!
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 从 Windows Forms 到微服务的经验教训
· 李飞飞的50美金比肩DeepSeek把CEO忽悠瘸了,倒霉的却是程序员
· 超详细,DeepSeek 接入PyCharm实现AI编程!(支持本地部署DeepSeek及官方Dee
点击右上角即可分享
微信分享提示