二分查找算法

来源:互联网 发布:电脑软件怎么安装 编辑:程序博客网 时间:2024/06/17 15:46

二分查找
时间限制:C/C++语言 1000MS;其他语言 3000MS
内存限制:C/C++语言 65536KB;其他语言 589824KB
题目描述:
请写一个二分查找算法查找一个数最先出现的index,如果数不在集合中需要返回(-1)-当前数应该出现的位置。例如 [1,3,6],查找5,5应该是在index=2的位置但并不在集合中。返回(-1)-2 = -3。
输入
第一行读入一个整数x,表示要查找的数;第二行读入一个正整数n,表示待查找数组的元素个数;第三行读入n个递增整数,构成待查找的数组。
输出
整数x在数组中出现的索引位置(索引从0开始计数);如果不存在,返回(-1)-当前数应该出现的位置。

样例输入
3
5
0 1 3 5 6
样例输出
2

#include<stdio.h>int a[100],number,n;int findIndex(int a[100],int find_number);int main(){ int find_number; scanf("%d\n",&find_number); scanf("%d\n",&n); for(int i=0;i<n;i++){     scanf("%d",&a[i]);  }int x;x=findIndex(a,find_number);printf("%d\n",x);}              int findIndex(int a[100],int find_number){    int low=0,high=n,gap;   gap=(low+high)/2;  //折半查找    while(low<=high){        if(a[gap]==find_number){               return gap;        }else if(a[gap]>find_number){              high=gap-1;              if(high<low){                 return (-1-low); //当没找到时,返回-1-(应该在的位置下标)              }        }else{             low=gap+1;             if(low>high){             return (-1-low);//当没找到时,返回-1-(应该在的位置下标)             }        }      gap=(low+high)/2;    }}
0 0