The hill sort was proposed by D.l.shell in 1959, and the relative direct ranking has been greatly improved. Hill sort is also called narrowing the incremental sort
Basic idea:
First, the entire sequence of records to be sorted into a number of sub-sequences of the direct insertion of the order, the entire series of records in the "Basic order", then the whole record is inserted in order.
Operation Method:
- Select an incremental sequence T1,T2,...,TK, where ti>tj,tk=1;
- According to the number of increment series K, the sequence is sorted by K-trip;
- Each order, according to the corresponding increment ti, the backlog sequence is divided into several sub-sequences of length m, respectively, the sub-table is directly inserted sort. Only the increment factor is 1 o'clock, the entire sequence is treated as a table, and the length of the table is the length of the entire sequence.
Example of a hill sort:
Algorithm implementation:
01.void print (int a[], int n, int i) {02. Cout<<i << ":"; The. for (int j= 0; j<8; j + +) {04. COUT<<A[J] << ""; 05.} 06. cout<<endl; 07.} 08./** 09. * Direct insertion of the general form of the sort 10. * 11. * @param int DK to reduce the increment, dk=1 12 If it is a direct insert sort. * 13. */14. 15.void shellinsertsort (int a[], int n, int dk)//Direct sort 16. {. for (int i= dk; i<n; ++i) {18. if (A[i] < A[I-DK]) {//If the first element is greater than the i-1 element, insert directly. Less then, move the ordered table after inserting 19. int j = I-DK; int x = A[i]; Copy to Sentinel, which stores the elements to be sorted 21. A[i] = A[I-DK]; First, move back one element 22. while (x < a[j]) {//Find the insertion position in the ordered table 23. A[J+DK] = A[j]; . J-= DK; The element moves back 25. } 26. A[J+DK] = x; Insert to the correct position 27. } 28. Print (A, n,i); 29.} 30. 31.} 32. 33./** 34. * First by Increment D (N/2,n is the number of orders to be sorted by Hill sort 35. * 36. */37.void Shellsort (int a[], int n)//Hill Sort
{38.39. int DK = N/2; (DK >= 1) {41. Shellinsertsort (A, n, DK); DK = DK/2; 43.} 44.} 45.int Main () {46. int a[8] = {3,1,5,7,2,4,9,6}; //shellinsertsort (a,8,1); Direct Insert Sort 48. Shellsort (a,8); Hill Insert Sort 49. Print (a,8,8); 50.}
Single-processing incremental sequence: Delta sequence d = {N/2, N/4, N/8 ..... 1} N is the number of digits to be sorted
That is: A set of records to be sorted by an increment D(the number of n/2,n to be sorted) into several sets of sub-sequences, each group of records of the subscript difference D. Direct Insert sorting of all elements in each group, followed by a smaller increment ( D/2) to group it, and then make a direct insert sort in each group. Continue to shrink the increment until it is 1, and finally use the direct insert sort to complete the sorting.
Hill sort (shell ' sort)