Java Hill sort

1. Basic concepts

    Basic idea: the algorithm first divides a group of numbers to be sorted into several groups according to a certain increment D (n/2,n is the number of numbers to be sorted), and the difference of subscripts recorded in each group is d,
    All elements in each group are directly inserted and sorted, then they are grouped with a small increment (d/2), and then directly inserted and sorted in each group,
    When the increment is reduced to 1, the sorting is completed after direct insertion sorting.

2. Algorithm analysis

    1. The array containing n elements is divided into n/2 array sequences. The first data and the n/2+1 data are a pair
    2. Compare and exchange each pair of data, and arrange the order;
    3. Then it is divided into n/4 array sequences and sorted again;
    4. Repeat the above process continuously. As the sequence decreases to 1, the sorting is completed.

3. Code implementation

public int[] sellSort(int[] arr){
    //int j;
    int temp;
    //How many sorts are used for records
    int k = 0;
    //Location for recording data exchange
    int flag;
    for (int increment  = arr.length / 2; increment  > 0 ; increment /=2) {
        System.out.println("The first"+(++k)+"Before sorting");
        System.out.println("increment :" + increment );
        for (int i = increment; i < arr.length; i++) {
            temp = arr[i];
            flag = i;
            for (int j = i - increment; j>=0; j-=increment) {
                if(temp < arr[j]){
                    System.out.println("temp: "+temp+" arr[j]: "+arr[j]+"; j: "+j+" ");
                    arr[j+increment] = arr[j];
                    //Record the location of data exchange
                    flag = j;
                }else{
                    break;
                }
                printArr(arr);
            }
            System.out.println("flag: "+flag);
            //arr[j + increment] = temp;
            arr[flag] = temp;
            printArr(arr);
        }
        System.out.println("The first"+k+"After sorting");
        printArr(arr);
        System.out.println();
    }
    return arr;
}

4. test

@Test
public void test(){
    int arr[] = {6,3,8,2,9,1};
    System.out.println("Before sorting");
    printArr(arr);
    int[] data = sellSort(arr);
    System.out.println("After sorting");
    printArr(data);
}

public void printArr(int[] arr){
    for (int i = 0; i < arr.length; i++) {
        System.out.print(arr[i]+" ");
    }
    System.out.println();
}

5. summary

    The key of hill sorting is not to sort the records randomly, but to form a subsequence of the records separated by a certain "increment" to realize leaping movement,
    The efficiency of sorting is improved. Note that the last increment value of the increment sequence must be equal to 1. In addition, because the record is a jumping movement,
    Hill sort is not a stable sort algorithm. 

Posted by aouriques on Fri, 03 Apr 2020 22:53:25 -0700