Insert Sort---Direct insert sort
int a[10];
for (int i=1;i<10;i++) {
if (A[i] < a[i-1])
{
int j = i-1;
int t = a[i];
while (T<a[j] && j>=0)
{
A[J+1] = A[j];
j--;
}
A[J+1] = x;
}
}
Time complexity: T (n) =o (n^2)
Insert Sort---hill sort
You should first understand the Hill sorting algorithm:
For example, suppose you have a group of numbers [13 14 94 33 82 25 59 94 65 23 45 27 73 25 39 10], and if we start with a step of 5, we can better describe the algorithm by placing the list in a table of 5 columns, so they should look like this:
13 14 94) 33 82
25 59 94) 65 23
45 27 73) 25 39
10
Then we sort each column:
10 14 73) 25 23
13 27 94) 33 39
25 59 94) 65 82
45
By connecting the four lines together, we get: [10 14 73 25 23 13 27 94 33 39 25 59 94 65 82 45]. Then 10 is moved to the correct position, and then the step is sorted by 3:
10 14 73
25 23 13
27 94 33
39 25 59
94 65 82
45
After sorting becomes:
10 14 13
25 23 33
27 25 59
39 65 73
45 94 82
94
The final sequence is sorted in 1 steps (this is a simple insert sort).
void print (int a[], int n, int i)
{
printf ("%d:", i);
for (int j=0; j<8; j + +)
{
printf ("%-3d", A[j]);
}
}
void Shellinsertsort (int a[], int n, int dk)
{
for (int i = DK; i<n; i++)
{
if (A[i] < A[I-DK])
{
int j = I-DK;
int x = A[i];
A[i] = A[I-DK];
while (x < a[j] && j>=0)
{
A[J+DK] = A[j];
J-=dk;
}
A[J+DK] = x;
}
Print (a,n,i);
}
}
void Shellsort (int a[], int n)
{
int DK = N/2;
while (DK >=1)
{
Shellinsertsort (A,N,DK);
DK/= 2;
}
}
int main ()
{
int a[8] = {3,4,2,1,5,3,1,9};
Shellsort (a,8);
Print (a,8,8);
}
Anatomy Insert Sort