Arrays - Bubble Sort Algorithm

one:

Use diagrams to explain bubble sort




Two: the basic implementation of the code

/**
     * 对无序的数组进行冒泡排序
     */
    public static void sort(int[] arr) {
        //外面的for循环控制的是比较的轮数
        //例如:6个元素的数组,要比较5轮
        for(int i = arr.length - 1;i > 0;i--){
            //里面的for循环控制的是每轮比较的次序
            for(int j = 0;j < i;j++){
                if(arr[j] > arr[j + 1]){
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325204950&siteId=291194637