zoukankan      html  css  js  c++  java
  • 折半插入排序

    #include"stdio.h"
    #include"stdlib.h"
    
    typedef struct SqList{
        int * elem;
        int length;
        int MaxSize;
    }SqList;
    
    void CreatList(SqList &L)
    {
        L.elem=(int *)malloc(100 * sizeof(int));
        if(!L.elem)
            exit(0);
        else
        {
            L.length = 0;
            L.MaxSize = 100;
            int i, n;
            printf("please shu ru yuan su ge shu:
    ");
            scanf("%d", &n);
            L.length = n;
            printf("please shu ru yuan su:
    ");
            for(i=1;i<=L.length;i++)
                scanf("%d", &L.elem[i]);
        }
    }
    
    void print(SqList L)
    {
        int i;
        for(i=1;i<=L.length;i++)
            printf("%d ", L.elem[i]);
        printf("
    ");
    }
    
    void InsertSort(SqList &L)         //对顺序表L直接插入排序
    {  
        
        int i, j;
        for(i=2;i<=L.length;++i)
            if(L.elem[i] < L.elem[i-1])
            {
                L.elem[0]=L.elem[i];
                for(j=i-1;L.elem[j]>L.elem[0];--j)
                    L.elem[j+1] = L.elem[j];
                L.elem[j+1] = L.elem[0];
            }
    }
    
    void BInsertSort(SqList &L)       //折半插入排序
    {
          int i, j, low, high, mid;
          for(i=2;i<=L.length;++i)
          {
              L.elem[0] = L.elem[i];
              low = 1;
              high = i-1;
              while(low <= high)
              {
                  mid = (low+high)/2;
                  if(L.elem[0] < L.elem[mid])
                      high = mid-1;
                  else
                      low = mid+1;
              }
              for(j=i-1;j>=high+1;--j)
                  L.elem[j+1] = L.elem[j];
              L.elem[high+1] = L.elem[0];
          }
    }
    
    int main()
    {
         SqList L;
         CreatList(L);
         print(L);
         //InsertSort(L);
         BInsertSort(L);
         print(L);
         return 0;
    }

    插入排序 是一种对原有序列排序的方法,逐步使原序列的有序序列增长

    折半插入排序 是在寻找 当前元素的位置时采取了折半查找的方法

  • 相关阅读:
    oracle 认证方式
    Oracle
    深入理解Java的接口和抽象类
    mongoDB的学习【小白的福音】
    对于vertical-align的学习
    flex的学习 flexBox的学习
    用伪类添加翘边阴影::before和::after
    icon小图标
    url 中的 ? 和 & 还有 # 的作用
    解决img的1px空白问题
  • 原文地址:https://www.cnblogs.com/wc1903036673/p/3500034.html
Copyright © 2011-2022 走看看