Hill sort — an efficient sorting algorithm

The direct insertion sort introduced in the previous article, it sorts the basically ordered data, and the efficiency will be very high, but if the original data is arranged in reverse order, the data needs to be moved for each comparison, which will reduce the efficiency of the algorithm .

      The basic idea of ​​Hill sorting is to divide the sequence to be sorted into several smaller sequences, and perform direct insertion sorting on these sequences. Through this operation, the sequence to be sorted can be basically ordered, and finally use a direct insertion sort.

      The first thing to be solved in Hill sorting is how to divide the sequence. The composition of the subsequence is not simply segmented, but to form a sequence of data separated by a certain increment. The general rule for selecting increments is: take half of the previous increment as the increment for this subsequence division, generally the total number of initial value elements.

  • Algorithm steps:

Initialize the array:

untitled.png

(1) Using half of the total number of elements (8) as an increment, divide the number into 8 sequences, and sort these 8 sequences respectively

untitled.png

(2) Reduce the increment by half (the value is 4), re-divide the subsequences to obtain 4 subsequences, sort these 4 subsequences respectively, and obtain the result after the second sorting.

image.png

(3) The reduction increment is 2, and the following results are obtained:

untitled.png

(4) The fourth pass increment is 1, and the final sorting result is obtained:

untitled.png

  • Code:

public class ShellSort {

  

   public static void main(String[] args) {

      int arr []={32,24,95,45,75,22,95,49,3,76,56,11,37,58,44,19,81};

      System.out.println("排序前:"+Arrays.toString(arr));

      sort(arr);

System.out.println ( " After sorting : " +       Arrays.toString ( arr ));

   }

   public static void sort(int arr[]) {

      int d=arr.length/2;

      int x,j,k=1;

      while(d>=1) {

         for(int i=d;i<arr.length;i++) {

            x=arr[i];

            j=i-d;

            //直接插入排序,会向前找所适合的位置

            while(j>=0 && arr[j]>x) {

                //交换位置

                arr[j+d]=arr[j];

                j=j-d;

            }

            arr[j+d]=x;

         }

         d=d/2;

         System.out.println(""+ k++ +"趟:"+Arrays.toString(arr));

      }

   }

}

排序前:[32, 24, 95, 45, 75, 22, 95, 49, 3, 76, 56, 11, 37, 58, 44, 19, 81]

1趟:[3, 24, 56, 11, 37, 22, 44, 19, 32, 76, 95, 45, 75, 58,   95, 49, 81]

2趟:[3, 22, 44, 11, 32, 24, 56, 19, 37, 58, 95, 45, 75, 76,   95, 49, 81]

3rd trip: [ 3 , 11, 32, 19, 37, 22, 44, 24, 56, 45, 75, 49, 81, 58, 95, 76, 95]

4th trip: [ 3 , 11, 19, 22, 24, 32, 37, 44, 45, 49, 56, 58, 75, 76, 81, 95, 95]

After sorting: [3, 11, 19, 22, 24, 32, 37, 44, 45, 49, 56, 58, 75, 76, 81, 95, 95]

Guess you like

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