Hill Sorting of Data Structures and Algorithms

We learned about insertion sort earlier. In this chapter, we will learn an upgraded version of insertion sort—Hill sort.

The basic idea of ​​Hill sort is a grouped insertion sort. First, we need to set a step gap (usually set to the length of the array divided by 2), and then when we need to sort the element i, just put... i+gap+gap,i+gap,i , i-gap, i-gap-gap.... These elements can be sorted by insertion (i+x*gap<n,iy*gap>=0).

Array to be sorted: 3,5,7,2,4,9,6,8,1,0

The first time: the step size is 5, the sixth element and the first element are a group for insertion sort, 3, 9.

                              The 7th element and the second element are a group for insertion sort, 5, 6.

                               The 8th element and the second element are a group for insertion sort, 7, 8.

                               The 9th element and the second element are a group for insertion sort, 1, 2.

                                The 10th element and the second element are a group for insertion sort, 0, 4.           


The second time: the step size is 2, and the five elements of the 1st, 3rd, 5th, 7th, and 9th are a group, and the insertion sort is performed.

                              The 2nd, 4th, 6th, 8th, and 10th elements are grouped together for insertion sort


The third time: gap=1, insert sorting for the entire array.


It is not difficult to write the code according to the schematic diagram.

public class ShellSort {
    /**
    *   @author:kevin
    * @Description: Basic sorting
    *   @Date:23:25 2018/4/2
    */
    public void sort(int[] arr, int n){
        for (int gap = n/2; gap>0; gap/=2) {
            for (int i = gap; i < n; i+=gap) {
                for (int j = i; j-gap>=0; j = j-gap) {
                    if (arr[j] < arr[j-gap]){
                        SortUtil.swap (arr, j, j-gap);
                    }
                }
            }
        }
    }
    /**
     *   @author:kevin
     * @Description: optimization
     *   @Date:23:25 2018/4/2
     */
    public void sort1(int[] arr, int n){
        for (int gap = n/2; gap>0; gap/=2) {
            for (int i = gap; i < n; i+=gap) {
                int j = i;
                int temp = arr[i];
                for (; j-gap>=0 &&temp < arr[j-gap]; j = j-gap) {
                    arr[j] = arr[j-gap];
                }
                arr[j] = temp;
            }
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325543560&siteId=291194637