First, let's talk about the basic idea of shell sorting: First take an integer D1 less than N as the first increment, and divide all the records of the file into D1 groups. All records whose distance is a multiple of DL are placed in the same group. Insert and sort data in each group first. Then, repeat the group and sort data in the second incremental D2 <d1 until the incremental dt = 1 (dt <DT-L <;... <D2 <d1), that is, all records are placed in the same group for direct insertion sorting.
The execution time of shell sorting depends on the incremental sequence.
Common Features of a good incremental sequence: ① The last increment must be 1; ② try to avoid the mutual multiples of values in the sequence (especially adjacent values.
In terms of time performance, the main reasons why Hill sorting is better than direct insertion are:
① When the initial state of the file is basically ordered, the number of comparisons and moves required for direct insertion sorting is relatively small. ② When the N value is small, the difference between N and N is also small, that is, the best time complexity of direct insertion of sorting O (N) and the worst time complexity 0 (N ^ 2) the difference is not big. ③ At the beginning of the hill sorting, there were a large increase in the number of groups and a small number of records in each group. Therefore, the number of records in each group was rapidly inserted. Later, the incremental di gradually reduced and the number of groups gradually reduced, the number of records in each group gradually increased, but because the di-1 has been used as the distance sorting order, the file is closer to the orderly state, so the new sorting process is also faster.
The following is a Shell Algorithm for sorting a group of randomly generated arrays. :
# Include <stdio. h> # include <stdlib. h> # include <time. h> # define max 10 # define swap (x, y) {int t; t = x; X = y; y = T;} void shellsort (INT []); int main (void) {int number [Max] = {0}; int I; srand (Time (null); printf ("Before sorting :"); for (I = 0; I <Max; I ++) {number [I] = rand () % 100; printf ("% d", number [I]);} shellsort (number); Return 0;} void shellsort (INT number []) {int I, J, K, Gap, T; Gap = max/2; while (GAP> 0) {for (k = 0; k <gap; k ++) {for (I = K + gap; I <Max; I ++ = gap) {for (j = I-gap; j> = K; j-= gap) {If (number [J]> Number [J + Gap]) {swap (number [J], number [J + Gap]);} else break ;}} printf ("\ NGAP = % d:", GAP ); for (I = 0; I <Max; I ++) printf ("% d", number [I]); printf ("\ n "); GAP/= 2 ;}}
From this code, we can find that the shell sorting algorithm is an unstable Sorting Algorithm because it is sorted by incremental grouping.