Hill sort, also known as the descending incremental sort algorithm, is a more efficient and improved version of insertion sort. But Hill sort is an unstable sort algorithm.
Hill sort is an improved method based on the following two properties of insertion sort:
- Insertion sort has high efficiency when it operates on almost ordered data, that is, it can achieve the efficiency of linear sort.
- But insert sort is generally inefficient because it can only move data one bit at a time;
The idea of Hill sorting is that the whole sequence of records to be sorted is divided into several sub-sequences for direct insertion sorting. When the records in the whole sequence are “basically ordered”, the whole sequence of records is directly inserted in order
A lot of people don’t understand what incremental means. For example, if the increment is 3, the element with subscript 0 is compared with the element with subscript 3, 3 is compared with 6, 1 is compared with 4, 4 is compared with 7… After the comparison, the increments are reduced again and the process is repeated until the increments are 1, at which point there is only one group left, and then the insertion sort is performed on that one group, and the whole Hill sort is finished.
- The initial increment value is set to 2/3 of the total.
- Starting at the increment position, compare the increment to the previous value. Example: The first element moves to the front with the smallest element compared to 2/3 of the table total. After the comparison, the starting position +1 continues.
- At the end of the comparison, the increment is halved and the second step is repeated until the number of intervals is 1.
Code implementation
- (void)shellSort:(NSMutableArray *)arr { int gap = (int)arr.count/2; // End the loop when gap==1while(gap >=1) {// Divide the gap elements into groups and scan all groupsfor(int i = gap; i < arr.count; Int temp = [arr[I] intValue]; int temp = [arr[I] intValue]; int j = i; // Sort the group of elements whose distance is gapwhile(j >= gap && temp < [arr[j - gap] intValue]) { [arr exchangeObjectAtIndex:j withObjectAtIndex:j-gap]; j -= gap; } } gap = gap/2; }}Copy the code
Algorithm analysis
Time complexity
The time complexity of Hill sort is related to the selection of increment (that is, step size gap). For example, when the increment is 1, hill sort degrades to direct insertion sort, where the time complexity is O(N²), whereas hill sort with Hibbard increment is O(N3/2).
Hibbard increment The recursive formula for Hibbard increment is H1 = 1, Hi = 2 * hi-1 + 1…… T = log2(n+1). If you want to know the NTH change, the formula is: the NTH change = 2(t-n+1) -1.
Spatial complexity
When we’re sorting, we need a temporary variable to store the values we’re inserting, so the space is O(1).