zoukankan      html  css  js  c++  java
  • 内部排序->插入排序->其它插入排序->折半插入排序

    文字描述

    和直接插入排序比较,只是把“查找”操作利用“折半查找”来实现,由此进行的插入排序叫做折半插入排序。

    示意图

    算法分析

    和直接插入排序比,减少了比较次数,但是移动次数没有变,所以折半插入排序算法的时间复杂度仍然是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("
    ");
    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

  • 相关阅读:
    26. 删除排序数组中的重复项
    巧记“指针数组”与“数组指针”
    在 VC 下清空键盘缓冲区的方法
    负数、取模与取余
    任意键开始、暂停
    int 越界处理
    防闪屏批量绘图
    VC 下如何正确的创建及管理项目
    CSDN博客步骤:
    61 扑克牌中的顺子
  • 原文地址:https://www.cnblogs.com/aimmiao/p/9346451.html
Copyright © 2011-2022 走看看