內部排序->插入排序->其它插入排序->折半插入排序

來源:互聯網
上載者:User

標籤:[]   include   空間   時間複雜度   display   技術   折半插入排序   none   alt   

文字描述

和直接插入排序比較,只是把“尋找”操作利用“折半尋找”來實現,由此進行的插入排序叫做折半插入排序。

 

略

 

演算法分析

和直接插入排序比,減少了比較次數,但是移動次數沒有變,所以折半插入排序演算法的時間複雜度仍然是n*n, 輔助空間為1,是穩定的排序方法。

 

代碼實現

 1 #include <stdio.h> 2 #include <stdlib.h> 3  4 #define EQ(a, b) ((a) == (b)) 5 #define LT(a, b) ((a) <  (b)) 6 #define LQ(a, b) ((a) <= (b)) 7  8 #define MAXSIZE 20 9 typedef int KeyType;10 typedef int InfoType;11 typedef struct{12     KeyType key;13     InfoType otherinfo;14 }RedType;15 16 typedef struct{17     RedType r[MAXSIZE+1];18     int length;19 }SqList;20 21 void PrintList(SqList L){22     int i = 0;23     printf("len:%d; data:", L.length);24     for(i=1; i<=L.length; i++){25         printf("%d ", L.r[i].key);26     }27     printf("\n");28     return ;29 }30 31 void BInsertSort(SqList *L)32 {33     int i = 0, j = 0;34     int low = 0, high = 0, m = 0;35     for(i=2; i<=L->length; ++i){36         L->r[0] = L->r[i];37         low = 1;38         high = i-1;39         while(low<=high){40             m = (low+high)/2;41             if(LT(L->r[0].key, L->r[m].key)){42                 high = m-1;43             }else{    44                 low = m+1;45             }46         }47         for(j=i-1; j>=high+1; --j){48             L->r[j+1] = L->r[j];49         }50         L->r[high+1] = L->r[0];51     }52 }53 54 55 int  main(int argc, char *argv[])56 {57     if(argc < 2){58         return -1;59     }60     SqList L;61     int i = 0;62     for(i=1; i<argc; i++){63         if(i>MAXSIZE)64             break;65         L.r[i].key = atoi(argv[i]);66     }67     L.length = (i-1);68 69     BInsertSort(&L);70     PrintList(L);71     return 0;72 }
折半插入排序

 

運行:

~$ ./a.out 3 5 7 3 1 9 6 4
len:8; data:1 3 3 4 5 6 7 9

內部排序->插入排序->其它插入排序->折半插入排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.