Bubble sort is a simple and direct sorting algorithm. It compares two adjacent elements in turn, swaps their values if they are in the wrong order, and then repeats the process until there are no elements to swap, that is, the sorting is complete.

Java implementation

        Integer[] arr = new Integer[]{43.77.29.39.66.83.104.93.11.10.18.27};

        for (int i = 1; i < arr.length; i++) {
            // Each loop can find a maximum value, such as the arR array, the first loop can find a maximum value of 104
            // The second inner loop finds the maximum value 93... The 11th inner loop finds the maximum value, 11, and the last element, 10, is the minimum value, without any comparison
            // So we have to run the length-1 inner loop in total, that is, the initial value of I is 1

            boolean flag = false;// Define an identifier that indicates whether an inner loop has been swapped

            for (int j = 0; j < arr.length - i; j++) {
                // The total length of the array is length, and the inner loop is to compare the first and last elements in sequence. In the first loop, the inner loop needs to compare length-1 times, so the initial value of I is 1
                // After the end of the first inner loop, a maximum value can be found, so the second loop can be compared 2 times less, that is, length-2 times
                // Thus, it can be inferred that when the outer loop is at the ith order, the inner loop needs to compare length-i times, that is, length-i
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    flag = true; }}if(! flag) {// If there is no swap at the end of an in-loop comparison, the array is sorted
                break; }}for (Integer integer : arr) {
            System.out.println(integer + ""); }}Copy the code

Output: 10 11 18 27 29 39 43 66 77 83 93 104

Algorithm steps

  1. Compare two adjacent elements and swap their values if the first is larger than the second. That is, the logic implemented inside the inner loop
  2. Compare each pair of adjacent elements and perform step 1 until the last pair. After the execution, the largest element is found. That’s the logic of the whole inner loop
  3. Repeat steps 1 and 2 until there are no elements to compare. That’s the logic of the whole outer loop