Direct insertion sort of Java's seven basic sorting

(1) Basic idea

Insert the records to be sorted into an already sorted ordered sequence one by one according to the size of their key values, until all records are inserted, and a new ordered sequence is obtained. (Similar to card sorting when playing poker)

When inserting the i (i>=1) element, the previous array[0], array[1],...,array[i-1] have been sorted. At this time, use the sorting code of array[i] and The sorting code order of array[i-1], array[i-2],... is compared. When the insertion position is found, array[i] is inserted, and the order of the elements at the original position is moved backward.

(2) Code implementation

public static void insertSort(int[] array) {
for (int i = 1; i < array.length; i++) {
            int tmp = array[i];
            int j = i-1;
            for (; j >= 0; j--) {
                if (array[j] > tmp) {
                    array[j + 1] = array[j];
                } else {
                    break;
                }
            }
            array[j + 1] = tmp;
        }
}
 

Below I call insertion sort in a new class and test:

(3) Feature summary

1. The more ordered the elements, the higher the efficiency;

2. The time complexity is O(N^2) and the space complexity is O(1);

3. It is a stable sorting

The above is all about direct insertion sorting. If you have any questions, please feel free to ask and discuss in the comment area!

 

Guess you like

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