Hill Sort (shellsort) is also called incremental decrement (diminishing increment) sorted by D.L. Shell invented, this algorithm is through a gradual decrease in the increment of an array gradually to the order to achieve the purpose of sorting.
Suppose there is an array int data[16] = {...}. The first increment is set to 16/2 = 8, which divides the array into 8 sub arrays, with indices of 0, 8 1, 9 2, 10, and so on. Sorts the child arrays. Then the increment is 8/2 = 4, so that the original array is divided into 4 sub arrays, and their indexes are 0, 4, 8, 12 1, 5, 9, 13, and so on. The four sets of numbers are then sorted until the increment is 1.
The incremental decrement described above is only one method, and this method is not the most efficient. such as f (n) = 3 * F (n-1) + 1 f (1) = 1 (..., 121, 40, 13, 4, 1) is better than the increment method above. The time complexity of this method is O (n ^1.5).
Algorithm is as follows
#include <stdio.h>
void output_array (int data[], int n)
{
int i;
for (i = 0; i < n; i++)
printf ("%d", Data[i]);
printf ("\ n");
}
void swap (int *a, int *b)
{
int x;
x = *a;
*a = *b;
*b = x;
}
void Insertion_sort (int data[], int n, int increment)
{
int i, J;
for (i = increment i < n; i + = increment) for
(j = i; j >= increment && data[j] > Data[j-increment] ; J-= increment)
swap (&data[j], &data[j-increment])
;
void Shellsort (int data[], int n)
{
int i, J;
for (i = N/2 i > 2; I/= 2) for
(j = 0; J < i; j +)
Insertion_sort (data + j, n-j, I);
Insertion_sort (data, n, 1);
}
int main ()
{
int data[] = {5, 3, 1, 665, 9, 8, 6};
Output_array (data,);
Shellsort (data,);
Output_array (data,);
return 0;
}
This article is from "Li Ning's Geek World" blog, please be sure to keep this source http://androidguy.blog.51cto.com/974126/215348