2 Java hill sort examples

  • 2020-04-01 03:17:53
  • OfStack

Java hill sort

Hill sort is a type of insertion sort, which can also be figuratively called the shrink increment method. The basic idea is to divide an array into several arrays, sort of like divide-and-conquer, but with a constant d.

The 0 < D< N,n is the length of the array. This is an improved algorithm with insertion sort speed, where if you have the smallest number at the end of the array, the insertion algorithm will override the last one

Moving the location to the first one is wasteful, and using this improved hill sort allows for a large span of movement of data elements. So that's what's nice about this algorithm.


package cn.cqu.coce.xutao;
public class shell3 {
 public static void main(String args[]){
  int a[]={7,43,23,5,3,2,0,6,74,9};
  int n=a.length;
  for(int i=0;i<n;i++)
   System.out.print(a[i]+"t");
  System.out.println();
     for(int gap=n/2;gap>0;gap/=2){
      for(int i=gap;i<n;i++){
       for(int j=i-gap;j>=0&&a[j]>a[j+gap];j-=gap){
        int temp=a[j+gap];
        a[j+gap]=a[j];
        a[j]=temp;
       }
      }
     }
  for(int i=0;i<n;i++)
   System.out.print(a[i]+"t");
  System.out.println();
 }
}


< img SRC = "border = 0 / / files.jb51.net/file_images/article/201405/20140507091946.jpg? 20144792058 ">

Second example


class Shell 
{
    public void shell_sort(int [] arrays){
        for(int d=5;d>0;d=d-2){
            for(int c=0;c<arrays.length-d;c++){
                for(int i=c;i<arrays.length;i=i+d){
                    for(int j=i;j>0;j=j-d){
                        if(j<d)
                            break;
                        if(arrays[j]<arrays[j-d]){
                            int tmp;
                            tmp=arrays[j];
                            arrays[j]=arrays[j-d];
                            arrays[j-d]=tmp;
                        }
                    }
                }

            }
            snp(arrays);
        }

    }
    public void snp(int[] arrays){
        for(int i=0;i<arrays.length;i++){
            System.out.print(arrays[i]+" ");
        }
        System.out.println();
    }
    public static void main(String[] args) 
    {
        Shell s=new Shell();
        int[] a={45,20,80,40,26,58,66,70};
        s.shell_sort(a);
    }
}

Operation results:


---------- java ----------
20 70 40 26 58 66 80 
20 58 45 26 70 66 80 
26 40 45 58 66 70 80 
 Output complete  ( Time consuming  0  seconds ) -  Normal termination 


Related articles: