折半查找

来源:互联网 发布:网络剧 有毒 全集 编辑:程序博客网 时间:2024/06/03 14:58
#include<stdio.h>#define N 15void sort(int *,int);void swap(int *,int *);int search(int *,int,int);int main(){    int i,num[N];    for(i=0;i<N;i++)        scanf("%d",num+i);    sort(num,N);/*首先先将数列排序*/    for(i=0;i<N;i++)        printf("%d ",*(num+i));/*查看排序结果*/    int find_num;    printf("input the num you want to find: ");    scanf("%d",&find_num);    int position;    position=search(num,N,find_num);/*查找并返回位置*/    if(position==-1)        printf("Not found!\n");    else        printf("the num %d is at position of %d\n",find_num,position);    return 0;}void sort(int *a,int n)/*选择排序*/{    int i,j,k;    for(i=0;i<n-1;i++)    {        k=i;        for(j=i+1;j<n;j++)            if(a[k]>a[j])                k=j;        if(k!=i)            swap(a+i,a+k);    }}void swap(int *a,int *b){    int temp;    temp=*a;    *a=*b;    *b=temp;}int search(int *a,int n,int num)/*折半查找*/{    int sign=0,loca,top,bottom,mid;    loca=0;/*用来记录所要查找数字位置信息的变量*/    top=0;/*开始位置*/    bottom=n-1;/*结束为止*/    if(num<a[0]||num>a[bottom])/*要查找的数字超过范围*/        loca=-1;    while((!sign)&&(top<=bottom))/*当没有找到时且开始位置在结束位置之前时执行*/    {        mid=(bottom+top)/2;/*数组的中间位置*/        if(num==a[mid])/*如果找到,则纪录位置,并将sign标记为已找到*/        {            loca=mid;            sign=1;        }        else if(num<a[mid])/*到前半段去找*/            bottom=mid-1;        else            top=mid+1;/*到后半段去找*/    }    if((!sign)||loca==-1)/*没找到要找的数字*/        return -1;    return loca+1;/*返回位置信息,由于人们习惯从1开始计数,将数组对应下标加一返回*/}

0 0
原创粉丝点击