Hill sort Shell Sort is an improvement based on the insertion sort, which is also divided into two parts,
The first part, Hill sort Introduction
The second part, how to choose the keyword, the key is to choose the key of hill sort
First piece of hill sort introduction
Preparing the array to be queued [6 2 4 1 5 9]
First you need to select keywords, such as the key is 3 and 1 (the first step is divided into three groups, the second step is divided into a group), then the array is divided into the following three virtual groups:
[6 1] a group
[2 5] two groups
[4 9] three groups
Look carefully, not close to the two number groupings, but 3 (divided into three groups) multiples of the number into a group,
That is, every 3 to take one, every three to take another, so that the number taken out into a group,
As a group, but not actually grouped, just as a group to see, so the upper "group" does not actually exist, just to illustrate the group relationship
Insert sort on the above three groups to change to the bottom
[1 6] [2 5] [4 9]
Specific process:
[6 1]6 and 1 switching becomes [1 6]
[2 5]2 and 5 not moving or [2 5]
[4 9]4 and 9 not moving or [4 9]
First Trip Sort status demo:
Arrays to be queued: [6 2 4 1 5 9]
Array after row: [1 2 4 6 5 9]
The second keyword to take is 1, that is, every other to make a new array, in fact, there is only one group, every one to take out all the
The array to be queued at this time is: [1 2 4 6 5 9]
Sort it directly into an insert
Remember the insertion sort?
[1 2 4] Do not move, the process is omitted, to 5, will be taken out of 5, in the ordered array in the front to find a suitable place to insert, 4 behind, 6 front
There's no need to change the back, so the sorting is complete
Sequential output results: [1 2 4 5 6 9]
The key to the second hill sort is how to take the keyword, because the other content is the same as the insertion sort
So how to choose keywords? is divided into three groups, a group, what is the basis of this grouping? Why not two groups, six groups or other groups?
Common characteristics of a good delta sequence:
① the last increment must be 1
② should try to avoid cases in which the values in the sequence (especially the neighboring values) are multiples of each other
The following C # code implementations are for informational purposes only
static void Shell_sort (int[] unsorted, int len) { int Group, I, J, temp; for (group = LEN/2; group > 0, Group/= 2) {for (i = group; i < Len, i++) {for (j = i-group; j >= 0; J-= Group) { if (Unsorted[j] > unsorted[j + Group]) { temp = unsorted[j]; UNSORTED[J] = unsorted[j + Group]; Unsorted[j + Group] = temp; }}}} static void Main (string[] args) { int[] x = {6, 2, 4, 1, 5, 9}; Shell_sort (x, x.length); foreach (var item in x) { Console.WriteLine (item); } Console.ReadLine (); }
Hill sort Shell Sort