1. 程式人生 > 實用技巧 >八大基本排序演算法----希爾排序

八大基本排序演算法----希爾排序

希爾排序(Shell Sort)


    • 前言:
      資料序列1: 13-17-20-42-28 利用插入排序,13-17-20-28-42. Number of swap:1;
      資料序列2: 13-17-20-42-14 利用插入排序,13-14-17-20-42. Number of swap:3;
      如果資料序列基本有序,使用插入排序會更加高效。

    • 基本思想:
      在要排序的一組數中,根據某一增量分為若干子序列,並對子序列分別進行插入排序。
      然後逐漸將增量減小,並重覆上述過程。直至增量為1,此時資料序列基本有序,最後進行插入排序。

    • 過程:

      • 平均時間複雜度:O(n^1.5)

      • java程式碼實現:

      • public static void shell_sort(int array[],int lenth){
        
           int temp = 0;
           int incre = lenth;
        
           while(true){
               incre = incre/2;
        
               for(int k = 0;k<incre;k++){    //根據增量分為若干子序列
        
                   for(int i=k+incre;i<lenth;i+=incre){
        
                       for(int j=i;j>k;j-=incre){
                           
        if(array[j]<array[j-incre]){ temp = array[j-incre]; array[j-incre] = array[j]; array[j] = temp; }else{ break; } } } } if(incre == 1){
        break; } } }