Direct insertion sort / binary insertion sort / Shell sort

--- --- restore content begins

Insertion sort are ordered in the case where the source data has been ordered. The time complexity of O (N ^ 2), stabilized

Direct insertion sort

code show as below

public  static  int [] insertSort ( int [] A) {
 IF (A == null || a.length == 0 ) {
 return A;}
 for ( int I =. 1; I <a.length; I ++ ) { 

for ( int J =-I. 1; J> = 0 && a [J]> a [+ J. 1]; J, ) 
  the swap (a, J, J + 1'd); // a front satisfy only exchange greater than a 
} 
A return; }

Half the premise is inserted into the original array are ordered

 

public static int[] subInser(int a[]) {
        for (int i = 1; i < a.length; i++) {
            int temp = a[i];
            int low = 0, high = i - 1;
            int mid = -1;
            while (low <= high) {
                mid = low + (high - low) / 2;
                if (a[mid] > temp) {
                    high = mid - 1;
                } else { //The same elements, but also inserted after position                 
                    Low = MID +. 1 ; 
                } 
            } 
            for ( int J = I -. 1; J> = Low; J, ) { 
                A [J +. 1] = A [J]; 
            } 
            A [Low] = TEMP; 
        } 
        return A; 
    }

Shell sort

No longer fixed-half the number of segments in d constant reduced until 1

 1  public static int[] shellsort(int [] a){
 2         int d=a.length/2;
 3         int tmp;
 4         while(d>0){
 5             for(int i=d;i<a.length;i++){
 6                 tmp=a[i];
 7                 int j=i;
 8                 while(j>d&&tmp<a[j-d]){
 9                     a[j]=a[j-d];
10                     j-=d;
11                 }
12                 a[j]=tmp;
13             }
14             d=d/2;
15         }
16      return  a;
17     }

 

Guess you like

Origin www.cnblogs.com/bowenqianngzhibushiwo/p/11619895.html