Java's seven major sorting bubble sorting (exchange sorting)

(1) Basic idea

Swapping is to swap the positions of the two records in the sequence based on the comparison results of the key values ​​​​of the two records in the sequence. The characteristics of swap sorting are: move the record with a larger key value to the end of the sequence, and move the record with a smaller key value to the end of the sequence . records are moved to the front of the sequence.

(2) Code implementation

In order to improve efficiency and optimize the code, define flg as false, which means that if this trip is ordered, there is no need to proceed to the next trip. And set j < array.length-1-i, not array.length.

public static void bubbleSort(int[] array) {
        for (int i = 0; i < array.length; i++) {
            boolean flg = false;
            for (int j = 0; j < array.length-1-i; j++) {
                if (array[j] > array[j+1]){
                    swap(array,j,j+1);
                    flg = true;
                } else {
                    break;
                }
            }
            if (flg == false) {
                return;
            }
        }
 }
    

(3) Feature summary

1. Time complexity: O(N^2) (without considering optimization) Space complexity: O(1)

2. Stability: stable

Guess you like

Origin blog.csdn.net/m0_56911648/article/details/130844877