Hill sort of Java advanced sort

  • 2020-04-01 03:49:35
  • OfStack

Hill sorting for as many as thousands of data items, medium size the size of the array sort well, hill sorting, unlike quick sort and other time complexity is O (n * logn) sorting algorithms so fast, therefore, the sort of very large files, it is not the best choice, but hill than selection and insertion sort this time complexity is O (n&sup 2) Sort is much faster, and it is very easy to implement, the code is short

Hill sorting is a kind of insertion sort, insertion sort, if the smallest number in the back, then copy too many times, and solved the problem hill, it is also a n - incremental sort, the idea is to insert the sorting of the interval of element, and in these elements with interval insertion sort, when these data items after a trip to sequence, hill sorting algorithms reduce the interval of data items sorted again, accordingly. The intervals between the data items when these sorts are made are called deltas and are customically represented by the letter h.

For an array that is about to be hill-sorted, the interval should be larger at first, and then not smaller until the interval is 1.

Interval sequence:

Interval sequence of digital quality is generally considered very important - they have no common divisor, except 1 this constraint conditions to make every trip to sort are more likely to keep the previous trip to sort has good effect, for different interval sequence, have an absolute condition, is to gradually reduce the interval of the last must be equal to 1. So the last train is a common insertion sort.

The following examples are derived from the rule that h=h*3+1:


package com.jll.sort;
public class ShellSort {
  int[] arr;
  int size;
  
  public ShellSort() {
    super();
  }
  
  public ShellSort(int size) {
    this.size = size;
    arr = new int[size];
  }

  
  public static void main(String[] args) {
    ShellSort ss = new ShellSort(10);
    for(int i=0;i<10;i++){
      ss.arr[i] = (int) ((Math.random()*100)+1);
      System.out.print(ss.arr[i]+" ");
    }
    ss.shellSort();
    System.out.println();
    System.out.println("after sort:");
    for(int i=0;i<10;i++){
      System.out.print(ss.arr[i]+" ");
    }
    
  }
  
  public void shellSort(){
    int h = 1;
    while(h<=size/3){
      h = h*3+1;
    }
    for(;h>0;h=(h-1)/3){
      for(int i=h;i<size;i++){
        int temp = arr[i];
        int j = i;
          while(j>h-1&&arr[j-h]>temp){
            arr[j]=arr[j-h];
            j-=h;
          }
          arr[j]=temp;
        }
      }
    }
  }

Related articles: