冒泡排序

Posted by t298 on May 11, 2021

冒泡排序

冒泡排序还是挺简的,主要思路就是两个元素互相比较,也就是说1号元素和2浩元素比较,小的放前面,大的放后面,接着是2号元素和3号元素比较,依次类推。

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void sort(int[] a,int n) { //a为需要排序的数组,n为数组长度
       int i,j;
       for (i=0;i<n;i++){ //这是比较次数
           for (j=1;j<n-i;j++){ //这是比较元素
               if (a[j-1]>a[j]){ //这是比较大小
                   int t;
                   t= a[j-1];
                   a[j-1] =a[j];
                   a[j] = t;
               }
           }
       }
}

如果这个数据只要一部分需要排序,比如“5,4,1,3,4,2,7,3,2,1,200,201,202,203,204”

那么就需要优化代码了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void sort(int[] a,int n) { //a为需要排序的数组,n为数组长度
        int j;
        int i = n;
       boolean flag = true; //定义一个条件判断是否排序的条件
       while (flag){
           flag = false; // 排序就是true,未排序就是False
           for (j=1;j<i;j++){
               if (a[j-1]>a[j]){
                   int t;
                   t = a[j-1];
                   a[j-1] = a[j];
                   a[j] = t;
                   flag = true;
               }
           }
           i--;
       }
    }

调用结果

1
2
3
4
5
6
7
public static void main(String[] args) {
        int[] a = {5,4,1,3,4,2,7,3,2,1,200,201,202,203,204};
        Test.sort(a, a.length);
        for (int b : a) {
            System.out.println(b);
        }
    } //1,1,2,2,3,3,4,4,5,7,200,201,202,203,204,