1. Insert sort-Direct insert sort (straight insertion sort)
Basic idea:
Insert a record into an ordered table that is already sorted, resulting in an ordered table with a new, 1 record count. That is, the first record of the sequence is considered to be an ordered subsequence, and then inserted from the second record one after the other until the entire sequence is ordered.
Important: set up Sentinel as a temporary storage and judgment array boundary.
Example of a direct insert sort:
If you encounter an element equal to the insert, the insertion element places the element you want to insert behind the equal element. So, the order of the equal elements is not changed, the order from the original unordered sequence is the order of the sequence, so the insertion sort is stable.
The implementation of the algorithm:
Packagesort; Public classInsertsort { Public Static voidMain (string[] args) {intA[] = {12,42,32,23,56,35,76,36,2}; Insertsort.sort (A,8); for(inti=0;i<a.length; i++) {System.out.print (A[i]+" "); } } Public Static voidSortint[] arr,intN) { for(intI=1; i<n; i++){ if(Arr[i] < arr[i-1]) {//if the first element is greater than the i-1 element, it is inserted directly. Otherwise, enter the ordered table to determine the insertion position after inserting intj = i-1;//is already the length of the row ordinal array intx = Arr[i];//set Sentinel to store elements with sortingArr[i]= Arr[i-1];//Move backward One while(X <Arr[j]) {Arr[j+1] = Arr[j];//Move backward Onej--; } arr[j+1] = x;//Insert to the correct location } } }}
Efficiency:
Complexity of Time: O (n²)
The other insert sort has two-insert sort, 2-way insert sort.
Sorting algorithm (ii)