thought : Each trip inserts a record into the appropriate position for a set of records that have been sequenced, knowing that the records to be sorted are inserted.
functionInsertsort (arr) { for(vari=2;i<=arr.length;i++){ if(Arr[i]<arr[i-1]) {//less than when insertingArr[0]=arr[i];//staging the records to be inserted to the lookoutARR[I]=ARR[I-1];//Arr[i-1] Move back for(varJ=I-2;ARR[0]<ARR[J];--J) {//looking for the insertion position from the back forwardARR[J+1]=ARR[J];//record-by-move, knowing where to find the insertion position} arr[j+1]=ARR[0];//Insert arr[0] i.e. original arr[i] into the correct position } } returnarr;}
Complexity of Time:
The basic operation for sorting is: compare two keywords and move. Best case: Positive order. Compare 1 times, do not move. Worst case: reverse. Compare I times (i-1 plus Sentinel), move i+1 times (i-1 plus move the insertion to the lookout and remove from the monitor). For the entire sort process: best case, the number of comparisons is n-1, not moving. Worst N^2/2 times, N^2/2 times. So the time complexity is O (n^2).
Complexity of space:
Only one record of the secondary space arr[0] is required, so the spatial complexity is O (1).
Algorithm Features:
1. Stable sorting.
2. Easy and easy to implement.
3. Also applies to chained storage structures.
4. More suitable for the initial record of the basic order of the situation. The initial record is unordered, n is large, the time complexity is high, and it is not applicable.
Sort algorithm-Insert sort (JavaScript)