Ten sorting algorithms - insertion sort

Direct insertion sort

  • The basic idea: the sequence of the first record considered as ordered, will turn back the record has been inserted into the sorted sequence.
  • Do: assume that the first has been ordered for each cycle after the element is inserted: if the small to large, that is greater than the value to be inserted if the end, the plug is not necessary. Otherwise looking forward from the end, until the value equals a [j]. Then of course, the insertion position is a [j + 1].
  • Code implements: Sentinel on \ (a [0] \)
    • Sentinel hold, then it would determine the boundariesa[i]<a[j] && j>=0
void insertsort(int a[], int n){
    for(int i=2;i<=n;i++){
        if(a[i]<a[i-1]){
            a[0] = a[i];
            for(int j=i-1; a[0]<a[j]; j--){
                a[j+1] = a[j];
            }
            a[j+1] = a[0];
        }
    }
}
  • Space complexity: \ (O (. 1) \) constant auxiliary space
  • Time complexity: Insert element \ (n-1 \) times, and compare each to move, which depends on the number of the original state to be sorted sequence
    • Best case: a sequence of ordered, each insert, only one comparison, without moving, \ (O (n-) \)
    • Worst case: reverse sequence, insertion elements \ (n-1 \) , with the total maximum number of comparisons \ (\ SUM \ limits_ I = {n-2} ^ {I} \) , the maximum total number of mobile \ (\ sum \ limits_ {i = 2} ^ n {(i + 1)} \)
    • Average case: random elements, the desired value can take the best worst average, and compare the total number of movements about the \ (n ^ 2/4 \ )
    • Whereby: direct insertion sort time complexity of the algorithm \ (O (n ^ 2) \) actually look at the code can also be seen
  • Stability: stable sort
    • Because it is relatively longer move forward from, so it will certainly encounter the same elements to stop, so the relative position will not change
  • Applicability: order and chain (you can also look back to front when the chain), most are only suitable for the sort order

Binary insertion sort

  • The place can be optimized: Find a smaller value than that in the ordered sequence, you can use half

Guess you like

Origin www.cnblogs.com/doragd/p/11291773.html