Chinaunix首页 | 论坛 | 博客
  • 博客访问: 523656
  • 博文数量: 118
  • 博客积分: 10028
  • 博客等级: 上将
  • 技术积分: 1820
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-07 18:46
文章分类

全部博文(118)

文章存档

2009年(12)

2008年(106)

我的朋友

分类: C/C++

2008-10-22 15:04:23


main函数中定义的a数组就是待查找数组s.list的初始化,MAXSIZE是元素个数,key是查找关键字.



#include <stdio.h>

#define MAXSIZE 10

typedef struct{
    int list[MAXSIZE];
    int length;
}List;

int dichotomy_search(List s,int k)
{
    int low,mid,high;
    low=0;
    high=s.length-1;
    mid=(low+high)/2;

    while(high>=low)
    {
        if(s.list[mid]>k){//turn to the left part

            high=mid-1;
            mid=(low+high)/2;
        }
        else if(s.list[mid]<k){ //turn to the right part

            low=mid+1;
            mid=(low+high)/2;
        }
        else
            return(mid+1);//The key has been searched

    }
    return 0;//no such key

}

int main(int argc,char **argv)
{
    List s;
    int i,k,rst;
    int a[MAXSIZE]={1,3,6,12,15,19,25,32,38,87};

    for(i=0;i<MAXSIZE;i++){
        s.list[i]=a[i];
    }
    s.length=MAXSIZE;

    printf("Input key number:");
    scanf("%d",&k);

    rst=dichotomy_search(s,k);
    if(rst==0){
        printf("Key:%d is not in the list!\n",k);
    }
    else{
        printf("The key is in the list,position is:%d \n",rst);    
    }
    return 0;
}

阅读(1322) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~