Algorithm summary - bubble sort

Posted by Aybabtu on Fri, 24 Dec 2021 20:16:43 +0100

Algorithm definition

Bubble sort is a kind of exchange sort and a relatively simple sort algorithm. According to the definition of encyclopedia, it repeatedly visits the element column to be sorted, compares two adjacent elements in turn, and exchanges them if the order is wrong. The work of visiting elements is repeated until no adjacent elements need to be exchanged, that is, the element column has been sorted. The name of this algorithm comes from the fact that the smaller elements will slowly float to the top of the sequence through exchange, just as the bubbles of carbon dioxide in carbonated drinks will eventually float to the top, so it is named "bubble sorting".

Algorithm principle

The principle of bubble sorting algorithm is as follows:

1. Compare a pair of adjacent elements. If the first element is larger than the second element, exchange the pair of elements.

2. Repeat step 1 for all adjacent elements, from the first pair of elements to the last pair of elements that are not determined. After this step, determine the maximum element of the current remaining elements.

3. Repeat steps 1 and 2 for fewer and fewer remaining elements until the maximum element of all currently remaining elements is determined.

code implementation

According to the above ideas, the preliminary code is as follows:

public class Main {

    // Bubble sort (swap sort), time complexity O(n^2), space complexity O(1)
    public static void bubbleSort(int[] arr) {
        // The number of times to sort is just the length of array arr minus 1. Find the current maximum number for each sort and move it to the corresponding position
        for (int i = 0; i < arr.length - 1; ++i) {
            // During each sorting, constantly compare the current element with the next element, and move the large element back
            for (int j = 0; j < arr.length - 1 - i; ++j) {
                if (arr[j] > arr[j + 1]) {
                    // If the current element is larger than the next element, exchange two elements
                    arr[j] ^= arr[j + 1];
                    arr[j + 1] ^= arr[j];
                    arr[j] ^= arr[j + 1];
                }
            }
        }
    }

}

However, the time complexity of the above code is fixed as O(n ^ 2). If the array is already ordered, it is redundant to exchange elements, or when the number of times of element exchange is halfway, the array becomes orderly, and it is redundant to exchange elements later. Therefore, the above code is defective and needs to be improved.

Suppose the length of the array is n.

Best case: if the array is ordered, there is no need to exchange elements. When the first layer for loop i = 0, carry out the second layer for loop. After the second layer for loop ends, it is judged that the array is ordered and ends. This process only goes once, but there is no element exchange, and the time spent each time is the order of N, so the time complexity in the best case is O(n).

Worst case: if the array is in reverse order, n - 1 times of element exchange is required, and the time spent for each time of element exchange is the order of N, so the time complexity in the worst case is O(n ^ 2).

Average case: the number of times in the average case can be expressed as N - 1 - k, and k is a constant. The time spent on element exchange in each time is also in the order of N, so the time spent in the average case is (n - 1 - k) * n, and the average time complexity = total time spent / the number of all cases. Because the number of trips is different in different cases, the number of all cases is equal to the order of N, the total time spent = the time spent in the average case * the number of all cases, that is, (n - 1 - k) * n * n, the average time complexity = the total time spent / the number of all cases = (n - 1 - k) * n * n / n = (n - 1 - k) * n, because k is a constant, Therefore, (n - 1 - k) * n is actually the order of magnitude of n ^ 2, so the average time complexity is O(n ^ 2).

According to the above analysis, the improved code is as follows:

public class Main {

    // Bubble sort improvement (exchange sort), average time complexity O(n^2), best time complexity O(n), worst time complexity O(n^2), space complexity O(1)
    public static void bubbleSort2(int[] arr) {
        // The number of times to sort is just the length of array arr minus 1. Find the current maximum number for each sort and move it to the corresponding position
        for (int i = 0; i < arr.length - 1; ++i) {
            // Determine whether the array is ordered
            boolean flag = true;

            // During each sorting, constantly compare the current element with the next element, and move the large element back
            for (int j = 0; j < arr.length - 1 - i; ++j) {
                if (arr[j] > arr[j + 1]) {
                    // If the current element is larger than the next element, exchange two elements
                    arr[j] ^= arr[j + 1];
                    arr[j + 1] ^= arr[j];
                    arr[j] ^= arr[j + 1];
                    // If there is an exchange, the array is not ordered
                    flag = false;
                }
            }

            if (flag) {
                // If array is already ordered, end loop
                break;
            }
        }
    }

}

Algorithm efficiency

Bubble sorting is a stable sorting algorithm. The best case is that the array is orderly, there is no need to exchange elements, only one time, and the time complexity is O(n); The worst case is that the array is in reverse order. Element exchange is required for each trip. Go through n - 1 times of element exchange, and the time complexity is O(n ^ 2); On average, according to the above calculation, the time complexity is O(n ^ 2); During element exchange, if the method of introducing intermediate variables is adopted, the intermediate variables occupy a space. The above code adopts the method of bit operation for element exchange without introducing intermediate variables. No matter which method is adopted, the space complexity is O(1).

Average time complexity: O(n ^ 2)

Best time complexity: O(n)

Worst time complexity: O(n ^ 2)

Space complexity: O(1)

reference material

Bubble sort dynamic chart from: Bubble sorting

Original link

Original link: Algorithm summary - bubble sort

Topics: Java Algorithm