The basic idea of a direct insert sort (Insertion sort) is to insert a record to be sorted each time, by its keyword size, into the appropriate position in the previously ordered subsequence until all records have been inserted.
set the array to a[0...n-1].
1. initially,A[0] self into 1 ordered areas, unordered area is a[1..n-1]. Make I=1
2. merge A[i] into an ordered interval of A[0...I] formed in the current ordered region A[0...i-1] .
3. i++ and repeat the second step until the I==n-1. Sorting is complete.
650) this.width=650; "src=" http://img.blog.csdn.net/20140918071958909 "/>
Code implementation:
//
Main.m
algorithm ---- insertion sort (insertion sort)
Copyright (c) year [email protected] All rights reserved.
//
#import<Foundation/Foundation.h>
int Main (int argc,const Char * argv[])
{
int array[] = {3,2, 6, 9, 8, 5, 7, 1, C10>4};
to increase portability ( take sizeof ()), count the number of array elements
int count = sizeof(array)/sizeof(array[0]);
Record one by one, insert an ordered series
for (int i = 1; i < count; i++) {
int j = i; //j is a pit that determines the position of the pit, and then takes the number out of the pit, paying attention to the order
int temp = array[i]; //temp is to take a number from the pit.
//Put A[i] into an ordered sequence
while (J > 0 && Temp < array[j-1]) { //j > 0 prevent out-of-bounds, write && front efficiency higher
ARRAY[J] = array[j-1];
j--;
}
ARRAY[J] = temp;
}
for (int i = 0; i < count; i++) {
printf ("[%2d]:%d\n", I, array[i]);
}
return 0;
}
Attached: Efficiency analysis
Stability
Space complexity O (1)
Time Complexity O (n2)
Worst case: Reverse order, need to move N (n-1)/2 elements
Best case: Positive order, no moving element required
The best time to insert sort efficiency is O (n)when the array is sorted or " approximate";
The insertion sort worst-case run time and average run time are O (n2).
In general, the insertion sort renders the best performance in two sorting algorithms.
For lists with fewer elements, such as n<=15, the two-time algorithm is very effective.
When the list has been sorted, the insertion sort is the linear algorithm O (n).
The insertion sort is still a linear algorithm when the list is " approximate sort " .
When many elements of a list are already in the correct position, the " approximate sort " condition appears.
Partial ordering of arrays by using an O (Nlog2N) efficiency algorithm (such as fast sorting)
Then select Sort, and some advanced sorting algorithms are implemented in this way.
From the above analysis, it can be seen that the direct insertion sort is suitable for the case that the number of records is relatively small and the given sequence is basically orderly
This article is from the "You Do not know" blog, please be sure to keep this source http://9217856.blog.51cto.com/9207856/1563523
Insertion sort of iOS algorithm (iii)