Java big data platform development study notes (10)-Hill (Shell) sort (optimized version)

1. Data structure and algorithm:


1.1. Create a Shell sort method:

 public static void shellShiftShot(int[] arr){
    
    
     for (int gap = arr.length /2; gap > 0; gap/=2) {
    
    
         for (int i = gap; i < arr.length; i++) {
    
    
             int value = arr[i];
             int index = i;
             while(index-gap >= 0) {
    
    
                 if (arr[index - gap] > value) {
    
    
                     arr[index] = arr[index - gap];
                 }else{
    
    
                     break;
                 }
                 index -= gap;
             }
             arr[index] = value;
         }
     }
 }
 

1.2. Optimization elements added by the above code:

    while(index - gap >= 0) {
    
    
        if (arr[index - gap] > value) {
    
    
            arr[index] = arr[index - gap];  //使用了 移位式,相较交换式进行了优化
        }else{
    
    
            break;  // 移位终止
        }
        index -= gap;	
    }
  

1.3, main method:

public static void main(String[] args) {
    
    
    //随机创建8万 个数据
    int arr[]= new int[80000];
    for(int i=0; i<arr.length; i++){
    
    
        arr[i] = (int)(Math.random()*80000);
    }
    //计算 冒泡排序时间
    double start = System.currentTimeMillis();
    System.out.println("计时开始:");
    shellShiftShot(arr);//此处写要测试的代码
    double end = System.currentTimeMillis();
    System.out.println("计时结束, 共耗时:"+ (double)((end-start)/1000) +"秒");
}
    

Written by ChiKong_Tam on September 10, 2020

Guess you like

Origin blog.csdn.net/qq_42209354/article/details/108507969