Sort-InsertionSort insert sort, sort-insertionsort
Insert sort implementation
Insert sorting is like a bet, such as a double button. When you draw a card, take one card at a time. This card is compared with the previous card. Select the position where the card is inserted, and sort the order to make the cards smoother. Otherwise, it may be difficult to find them one by one. It is not conducive to playing cards. View
Assume that plum blossom 7 is drawn for the first time without sorting. Because there is only one
Then draw plum blossom 10. Because 10 is bigger than 7, no sorting is required.
And then draw the cards. Found that the plum blossom 5. Don't hesitate at this time. is really not big. Discard card decisively
Then we compare the values of 5 and 10. 5 is less than 10, so the switching position.
Compare 5 to 7. 5 is smaller than 7. Therefore, you can obtain the values at the locations of 5 and 7.
This is already sorted. This is how it works.
Because it is relatively simple. Directly paste the code
// O (n ^ 2) Worst Case // best case O (n) public static void sort (Comparable [] a) {for (int I = 1; I <. length; I ++) {for (int j = I; j> 0; j --) {if (less (a [j], a [j-1]) exch (a, j, j-1); else break ;}} public static void sort (Comparable [] a, int low, int hi) {for (int I = low; I <= hi; I ++) {for (int j = I; j> low; j --) {if (less (a [j], a [j-1]) exch (a, j, j-1); else break ;}}}
InsertSort
Complete code in https://github.com/Cheemion/algorithms/blob/master/src/com/algorithms/sort/InsertionSort.java
Performance Analysis
The worst case is that every time the card is drawn, it is the smallest. At this time, you need to traverse from the tail to the header each time. Time is proportional to N ^ 2
The best case is that the order has been sorted. Because the order has been sorted. Therefore, the Cards drawn each time do not need to be sorted. Time is proportional to N