An implementation of a direct insert sort:
Publicilist<int> Insertionsort (int[] ary) { varLen =ary. Length; for(inti =1; i < Len; i++) { varKey =Ary[i]; for(intj =0; J < I; J + +)//look backwards from the front . { if(Key <Ary[j]) { for(intK = i; K > J; k--)//move forward one after the other{Ary[k]= Ary[k-1]; } Ary[j]=key; Break;//each time a value is inserted, this traversal is completed } } } returnary. ToList (); }
This approach, which is from small to large (left to right), looks for the insertion position, for Each loop, in the list that is already lined up, find "first", a number larger than the current value to be inserted, and then start at the last position, move from right to left, and empty the position of the number larger than the current value, and insert the current value. And then end the cycle of this time. Looking at the code reveals that this is a slightly more complex way to write.
Another way to do this is to find the insertion position from large to small (right-to-left) in the order of the Code:
Publicilist<int> Insertionsort (int[] ary) { varLen =ary. Length; for(inti =1; i < Len; i++) { varKey =Ary[i]; intj = i-1; while(J >=0&& key < Ary[j])//move from the back to the side{ary[j+1] =Ary[j]; J--; } ary[j+1] =key; } returnary. ToList (); }
An outer loop, like an inner loop, moves each time from the last ordered element, using the while side to compare. If the sorted value is less than the value currently being inserted, the loop is ended. The position to be inserted is also painful, just insert the current value. This is because each time you do a j--, you need to add 1 when inserting.
The direct insertion sort is characterized by the use of "constant" additional memory space, which is the space complexity of O (1). And the time complexity is O (n*n).
Insert Sort--1 Direct Insert sort implementation