Hill sort is strictly based on the idea of insertion sorting, also known as narrowing the incremental sort. The process is as follows: 1, an array containing n elements, divided into N/2 sequence, the first data and the n/2+1 data is a pair ... 2, the comparison and exchange of each pair of data, arranged in order; 3, then divided into N/4 sequence, again sorted, 4, repeating the above process, with the sequence reduced and up to 1, sorting completed. If there is initial data: 25 11 45 26 12 78. 1, the first round of sorting, the array is divided into 6/2=3 sequence, the 1th data and 4th data is a pair, 2nd data and 5th data is a pair, 3rd data and 6th data is a pair, each comparison of the data sorted, sorted after the order: [25, 11, 45, 26, 12, 78]. 2, the second round of sorting, will be sorted on the upper line of the array into a sequence of 6/4=1, at this time, one by one to compare the data, sorted by the insertion sort of the array, the order is: [11, 12, 25, 26, 45, 78]. For the insertion sort, if the original array is basically ordered, the sorting efficiency can be greatly improved. In addition, the use of direct insertion sorting for a smaller number of sequences increases the efficiency of the data that needs to be moved less. As a result, hill sequencing has a high execution efficiency. Hill sort is not stable, O (1) extra space, time complexity is O (n (logn) ^2). The Java code is implemented as follows: (Https://github.com/xbk417/algorithm)
1 Public voidSortint[] arr) {2 //I represents the n/2+1 element (or n/4+1) in a hill sort3 //J represents the element from 0 to N/2 in the hill Sort (N/4)4 //R represents the value of n/2+1 or n/4+1 in the hill sort5 intI, J, R, TMP;6 //Sorting Groups7 for(r = ARR.LENGTH/2; r >= 1; r = R/2) {8 for(i = r; i < Arr.length; i++) {9TMP =Arr[i];Tenj = i-R; One //round a sort A while(J >= 0 && tmp <Arr[j]) { -ARR[J+R] =Arr[j]; -J-=R; the } -ARR[J+R] =tmp; - } -SYSTEM.OUT.PRINTLN (i + ":" +arrays.tostring (arr)); + } -}
The Java implementation of the common algorithm hill sort