The idea of direct insertion: each time the records to be sorted are inserted into the set of records in front of them by keyword, until the end!
Give a simple example:
The array to be sorted is: [2] 5 9 8 6 1
First time: [2 5] 9 8 6 1
Second time: [2 5 9] 8 6 1
Third time: [2 5 8 9] 6 1
Fourth time: [2 5 6 8 9] 1
Fifth time: [1 2 5 6 8 9]//End
Core code:
for (int i=2,j;i<=numbers.length-1;i++) {numbers[0]=numbers[i];j=i-1;while (Numbers[0]<numbers[j]) {numbers[j +1]=NUMBERS[J]; j--;} Numbers[j+1]=numbers[0];}
Compare the core code to see the algorithm implementation steps:
-
Save the record to be sorted to the flag bit number[0]
-
J=i-1, which is used to insert into a previously lined recordset
-
The current record corresponding to the J position is moved backward when the termination condition is not satisfied, and J moves forward one
-
Termination condition: Flag bit or meet condition position
The analysis of the algorithm:
-
Stability: Stable
-
Complexity of Time:
The original data does not need to be moved in the positive order, total comparison: n-1, i.e. O (n)
The original data is moved frequently in reverse order, total comparison: (n*n+n-2)/2, i.e. O (n*n)
The original data is unordered, the average number of comparisons for the first trip is: (i+1)/2, Total (n*n+3*n)/4, i.e. O (n*n)
Therefore, the more the data tends to be in the positive order, the less the number of comparisons and the least number of moves (applicable)
-
Space complexity: Just waste a unit, numbers[0];
Direct Insert Sort