二分插入排序与检索

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define num 50
typedef int keytype;
typedef int datatype;
typedef struct
{
    keytype key;
}dictelement;
typedef struct
{
    int n;
    dictelement *element;
}seqdictionary;
void binsort(seqdictionary *pvector)
{
    int i,j,left,right,mid;
    dictelement temp;
    dictelement*data=pvector->element;
    for(i=1;i<pvector->n;i++)
    {
        temp=data[i];
        left=0;
        right=i-1;
        while(left<=right)
        {
            mid=(left+right)/2;
            if(temp.key>data[mid].key) right=mid-1;
            else left=mid+1;
        }
        for(j=i-1;j>=left;j--)
            data[j+1]=data[j];
        if(left!=i)
            data[left]=temp;
    }
}
int binnarysearch(seqdictionary *a,int key)
{
    int low,mid,high,count=0;
    low=0;high=a->n-1;
    while(low<=high)
    {
        mid=(low+high)/2;
        count++;
        if(a->element[mid].key==key)
        {
            printf("比较了%d次\n",count);
            return 1;
        }
        else if(a->element[mid].key<key)
            high=mid-1;
        else low=mid+1;
    }
    if(low>high)
    {
        printf("比较了%d次\n",count);
        return 0;
    }
}
int main()
{
    seqdictionary *mysort;
    int mykey,i,key,post;
    srand(time(NULL));
    mysort=(seqdictionary*)malloc(sizeof(seqdictionary));
    if(mysort!=NULL)
    {
        mysort->element=(dictelement*)malloc(sizeof(dictelement)*num);
        if(mysort->element) mysort->n=num;
    }
    printf("要排序的数为\n");
    for(i=0;i<num;i++)
    {
        mykey=rand()%150;
        mysort->element[i].key=mykey;
        printf("%4d",mykey);
    }
    printf("\n\n");
    printf("用二分插入排序后为:\n");
    binsort(mysort);
    for(i=0;i<num;i++)
    {
        printf("%4d",mysort->element[i].key);
    }
    printf("\n\n");
    printf("请输入你要查找的值\n");
    scanf("%d",&key);
    post=binnarysearch(mysort,key);
    if(post==1)
        printf("%d\n\n检索成功,里面有该数值\n",post);
    else
        printf("%d\n\n检索不成功,里面没有该数值\n",post);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值