table of Contents
From the direct insertion sort to sort Hill
Direct insertion sort, it works prior to the sequence length becomes i ordered sequence, then a loop iteration, until the entire sequence of both become ordered. But it still comes down to a time complexity (n ^ 2) algorithm, can no longer further the time complexity of a lower-order it?
Hill is sorted Hill (Donald Shell) proposed in 1959 a kinds of sorting algorithms. Hill is also a sort insertion sort, it is the direct insertion sort through a more efficient version of the following improvements , also known as narrow increment sort, while the algorithm is breaking the O (n2) one of the first algorithm.
The starting point of the algorithm thought :( direct insertion sort)
- When basic ordering, higher efficiency
- When the number of records to be sorted is small, high efficiency
Then: first the whole row to be recorded sequence into several sub-sequences , respectively direct insertion sort, until the entire recording sequence "substantially orderly" , then all the records of a direct insertion sort .
Sequence is all distances dk multiple recording (the detailed procedure below)
Compared with direct insertion sort, Shell sort dividing a multi-step sequence. Contrast direct insertion sort and shell sort of code that can be easily understood Hill algorithm.
Flow algorithms Hill
In a specific example to understand the whole algorithm:
[Initial state: the input data, dk step size, i.e., increment] sliced
from the beginning of the process result of the first pass to the state (in ascending order):
[Yellow: the initial state and the data packet sequence in the first pass, red: a first trip and a second trip series Results] Results
from the first pass to the second pass results results (in ascending order):
- A method for sorting unstable
- A sort of position after the element is not in the position on the final result
Performance analysis algorithms Hill
- Space Complexity: S(n)=O(1)
- Time Complexity: incremental sequence depends on (mean better performance than direct insertion sort)
Code
int shellSort(int arr[], int n)
{
//gap为每一趟的长,倍减
for (int gap = n/2; gap > 0; gap /= 2)
{
// gap sorted(直接插入排序)
for (int i = gap; i < n; i += 1)
{
// 直接排序从下标为零的元素开始
int temp = arr[i];
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
arr[j] = arr[j - gap];
// put temp (the original a[i]) in its correct location
arr[j] = temp;
}
}
return 0;
}
Knowledge examination
- Hill sorting process
- Forward: write a trip sort results
- Reverse: inferred incremental interval according to the ranking result
- Hill sorting features
- Sort unstable
- Local order (sort each trip may not be a final element in a direction opposite positions)