posts - 63, comments - 37, trackbacks - 0, articles - 0
  IT博客 :: 首页 :: 新随笔 :: 联系 ::  :: 管理

折半插入查找代码实现

Posted on 2006-06-14 09:49 Enjoy Life 阅读(344) 评论(0)  编辑 收藏 引用 所属分类: DS study

#include <stdio.h>

#include <stdlib.h>

 

#define MAXSIZE 20

#define MAX_LENGTH 100

 

typedef int RedType;

typedef struct SqList{

       RedType r[MAXSIZE+1];

       int length;      

}SqList;

 

// 此处用指针或者引用都可以,但是不能直接用结构来作为参数传人 InsertSort(SqList &L):OK  InsertSort(SqList L):ERROR, 没法正常工作

void BiInsertSort(SqList *L) 

{  int i,j,low,high,mid;

   for(i=2;i<=L->length;++i)

       if(L->r[i]<L->r[i-1]){

                     L->r[0] = L->r[i];

                     high=i-1;

                     low=1;

                     while(low<=high){

                            mid=(low+high)/2;

                            if(L->r[0]<L->r[mid])

                                   high=mid-1;

                            else

                                   low=mid+1;

                     }

                     for(j=i-1;j>=high+1;--j)

                            L->r[j+1]=L->r[j];

                     L->r[high+1]=L->r[0];

          }

 

}

 

 

 

/*

用结构来做,比较常用

void main()

{

       int i;

       SqList L;

       printf("\nPlease input the length you want to sort\n");

       scanf("%d",&L.length);

       for(i=1;i<=L.length;i++){

              printf("\nPlease input the %dth data\n",i);

              scanf("%d",&L.r[i]);

       }

       printf("\nYou input data is:");

       for(i=1;i<=L.length;i++)

              printf("%5d",L.r[i]);

       BiInsertSort(&L);

       printf("\nThe sorted data is:");

       for(i=1;i<=L.length;i++)

              printf("%5d",L.r[i]);

      

}

*/

 

// 用指针来做

void main()

{

       int i;

       SqList *L;

       if(!(L=(SqList *)malloc(sizeof(SqList)))){

              printf("OverFlow\n");

              return;

       }

       printf("\nPlease input the length you want to sort\n");

       scanf("%d",&L->length);

       for(i=1;i<=L->length;i++){

              printf("\nPlease input the %dth data\n",i);

              scanf("%d",&L->r[i]);

       }

       printf("\nYou input data is:");

       for(i=1;i<=L->length;i++)

              printf("%5d",L->r[i]);

       BiInsertSort(L);

       printf("\nThe sorted data is:");

       for(i=1;i<=L->length;i++)

              printf("%5d",L->r[i]);

       free(L);

      

}

只有注册用户登录后才能发表评论。