冒泡排序

  冒泡排序顾名思义就是整个排序过程像气泡一样上升,其基本思想是(假设由小到大排序):对于给定的n个记录,

从第一个记录开始依次对相邻的两个记录进行比较,当前面的记录大于后面的记录时,交换位置,进行一轮比较和换位后,

n个记录中的最大记录将位于第n位;然后对前(n-1)个记录进行第二轮比较;重复该过程直到进行比较的记录只剩下

一个为止。

  通俗点来说就像是滚石子,石子两两比较,比后面的石子大就滚的过去,否则就停下来,让大的石子继续滚

代码实现:

public class TestSort {
    public static void bubbleSort(int[] arr) {
        int temp = 0;
        for (int i = 0; i < arr.length - 1; i++) { //只需要排arr.length-1趟,因为最后一个肯定是最小的
            for (int j = 0; j < arr.length - 1 - i; j++) {//第i+1趟排序只需要比较arr.length-1-i次
                if (arr[j + 1] < arr[j]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {5, 3, 6, 1, 4, 7, 2, 9, 8};
        bubbleSort(arr);
        for (int anArr : arr) {
            System.out.print(anArr);
        }
    }
}

输出结果:

原文地址:https://www.cnblogs.com/wutongshu-master/p/10868491.html