First, take an integer less than n D1 as the first increment, dividing all the records of the file into D1 groups. All records that are multiples of the DL are placed in the same group. The direct insert sort is performed in each group first, then the second increment d2<d1 repeats the above groupings and sorts until the increment dt=1 (DT<DT-L<;...<D2<D1) is taken, that is, all the records are placed in the same group for direct insert sorting. This method is essentially a grouping insertion method. Schematic diagram: Source code
1 Package Com.zc.manythread;2 /**3 * 4 * @author even my yes5 *6 */7 Public classShellsort {8 Public Static intCount =0;9 Ten Public Static voidShellsort (int[] data) { One //calculates the maximum h value A inth =1; - while(H <= data.length/3) { -H = h *3+1; the } - while(H >0) { - for(inti = h; i < data.length; i + =h) { - if(Data[i] < data[i-h]) { + intTMP =Data[i]; - intj = i-h; + while(J >=0&& Data[j] >tmp) { AData[j + h] =Data[j]; atJ-=h; - } -Data[j + h] =tmp; - print (data); - } - } in //calculate the next H value -h = (H-1) /3; to } + } - the Public Static voidPrintint[] data) { * for(inti =0; i < data.length; i++) { $System. out. print (Data[i] +"\ t");Panax Notoginseng } -System. out. println (); the } + Public Static voidMain (string[] args) { A the int[] data =New int[] {4,3,6,2,1,9,5,8,7 }; + print (data); - shellsort (data); $ print (data); $ - } -}
Operation Result:
The shell sort is unstable, its space overhead is also O (1), and the time overhead is estimated between O (N3/2) ~o (N7/6)
Shell sort (hill) algorithm--java