二分搜索

来源:互联网 发布:车子天窗有必要吗 知乎 编辑:程序博客网 时间:2024/06/08 00:13
#include<stdio.h>#include<math.h>#define N 5int a[N];void quicksort(int left,int right){    int i,j,t,temp;    if(left>right)        return;    t=a[left];    i=left;    j=right;    while(i!=j)    {        while(t<=a[j]&&i<j)            j--;        while(t>=a[i]&&i<j)            i++;        if(i<j)        {            temp=a[i];            a[i]=a[j];            a[j]=temp;        }    }    a[left]=a[i];    a[i]=t;    quicksort(left,i-1);    quicksort(i+1,right);    return;}void binarysearch(int x,int left,int right){    int i,j,mid;    i=left;    j=right;    while(i<=j)    {        mid=(i+j)/2;        if(x>a[mid])            i=mid+1;        else if(x<a[mid])            j=mid-1;        else if(x==a[mid])        {            printf("%d\n",mid+1);            return;        }    }    return;}int main(int intval,char **charval){    register int i;    for(i=0; i<N; ++i)        scanf("%d",&a[i]);    quicksort(0,N-1);    int x;    scanf("%d",&x);    binarysearch(x,0,N-1);    return 0;}
0 0
原创粉丝点击