Java data structure and algorithm (6) - Hill sorting

Posted by Tokunbo on Fri, 01 May 2020 03:45:10 +0200

1, Generation of hill ordering

The shell sort is Insert sort One of. Also known as reduction increment Sorting is an improved version of direct insertion sorting algorithm. Hill sort is an unstable sort algorithm. This method was named after DL. Shell in 1959.
Hill sorting is to group records by a certain increment of subscript, and use the direct insertion sorting algorithm to sort each group. As the increment gradually decreases, each group contains more and more keywords. When the increment is reduced to 1, the whole file is just divided into a group, and the algorithm is terminated.

2, Hill's ranking is based on the following two properties of insertion ranking

Insert sorting is efficient when it is used to sort almost sorted data, that is to say, it can achieve the efficiency of linear sorting.
But insert sorting is generally inefficient, because insert sorting can only move data one bit at a time.

public static void main(String [] args)
{
    int[]a={49,38,65,97,76,13,27,49,78,34,12,64,1};
        System.out.println("Before sorting:");
        for(int i=0;i<a.length;i++)
        {
            System.out.print(a[i]+" ");
        }
        //Shell Sort 
        int d=a.length;
            while(true)
            {
                d=d/2;
                for(int x=0;x<d;x++)
                {
                    for(int i=x+d;i<a.length;i=i+d)
                    {
                        int temp=a[i];
                        int j;
                        for(j=i-d;j>=0&&a[j]>temp;j=j-d)
                        {
                            a[j+d]=a[j];
                        }
                        a[j+d]=temp;
                    }
                }
                if(d==1)
                {
                    break;
                }
            }
            System.out.println();
            System.out.println("After sorting:");
                for(int i=0;i<a.length;i++)
                {
                    System.out.print(a[i]+" ");
                }
    }

perhaps

package com.fantj.dataStruct.shellSort;

/**
 * Created by Fant.J.
 * 2017/12/21 20:49
 */
public class ShellSort {
    /**
     * Sorting method
     */
    public static void sort(long []arr){
        //Initialize an interval
        int h =1;
        //Calculate maximum interval
        while (h < arr.length/3){
            h = h * 3 + 1;
        }
        while (h > 0){
            //Sort insert
            long temp = 0;
            for (int i = 1; i< arr.length ;i++){
                temp = arr[i];
                int j = i;
                while (j>h-1 && arr[j-h] >= temp){
                    arr[j] = arr[j-1];
                    j -= h;
                }
                arr[j] = temp;
            }
            //Decrease interval
            h = (h -1) / 3;
        }
    }
}

Topics: shell