Algorithm - bubble sorting

Bubble sort: sort arrays in ascending or descending order.

Principle: (take ascending order as an example)

Use double loop to compare the two adjacent numbers in the array in turn, putting the decimal first and the large number second.

The first time: first, compare the first and second numbers, put the decimal number before and the large number after. Then compare the second and third numbers, put the decimal number before and the large number after. And so on until the last two numbers are compared. At the end of the first run, put the maximum number at the end.

Second pass: still compare the first and the second numbers (because the exchange position of the second and the third numbers may make the first number no longer less than the second number). Put the decimal number before and the large number after. And so on, until you compare to the next to last (the first to last is already the largest). At the end of the second pass, a new maximum number (actually the second largest number in the whole sequence) is obtained at the position of the second to last.

And so on until the final sorting is completed, which is ascending.

 

Two ways: ascending and descending

    /**
     * Bubble sort (ascending)
     * @param arr   Sorted array
     */
    public static void bubbleSortUp(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {//Bubble times
            for (int j = 0; j < arr.length - 1 - i; j++) {//Times of bubbling
                //Position exchange
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    /**
     * Bubble sort (descending)
     * @param arr   Sorted array
     */
    public static void bubbleSortDown(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {//Bubble times
            for (int j = 0; j < arr.length - 1 - i; j++) {//Times of bubbling
                //Position exchange
                if (arr[j] < arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

verification

int[] arr = {11,9,22,66,44};
bubbleSortUp(arr);
LogUtil.e("Bubble sort (ascending)", Arrays.toString(arr));//[9, 11, 22, 44, 66]

int[] arr1 = {11,9,22,66,44};
bubbleSortDown(arr1);
LogUtil.e("Bubble sort (descending)", Arrays.toString(arr1));//[66, 44, 22, 11, 9]

 

Keywords: less

Added by dw89 on Mon, 16 Dec 2019 23:12:26 +0200