查找 发表于 2018-03-15 | 分类于 算法 顺序查找和二分查找 说明:代码使用codeblocks编译,C++实现,个人编写,如有错误,还望指正。 二分查找要求输入的数据是有序的。如果有重复的元素,查找到的未必是最前面的。 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556#include <iostream>using namespace std;//顺序查找//找到返回下标,没找到返回-1;int order_search(int array[],int len,int val){ for(int i=0;i<len;i++) { if(array[i]==val) return i; } return -1;}//二分查找//找到返回下标,没找到返回-1;int binsearch(int array[],int len,int val){ int low=0; int high=len-1; int mid=0; while(low<=high)//注意要有= { mid=(low+high)/2; if(array[mid]==val) return mid; else if(array[mid]>=val) high=mid-1; else low=mid+1; } return -1;}int main(){ int a[]={10,11,12,13,14,15,16,17,18,19}; cout<<order_search(a,sizeof(a)/sizeof(a[0]),13)<<endl; cout<<binsearch(a,sizeof(a)/sizeof(a[0]),9)<<endl; cout<<binsearch(a,sizeof(a)/sizeof(a[0]),10)<<endl; cout<<binsearch(a,sizeof(a)/sizeof(a[0]),11)<<endl; cout<<binsearch(a,sizeof(a)/sizeof(a[0]),12)<<endl; cout<<binsearch(a,sizeof(a)/sizeof(a[0]),13)<<endl; cout<<binsearch(a,sizeof(a)/sizeof(a[0]),14)<<endl; cout<<binsearch(a,sizeof(a)/sizeof(a[0]),15)<<endl; cout<<binsearch(a,sizeof(a)/sizeof(a[0]),16)<<endl; cout<<binsearch(a,sizeof(a)/sizeof(a[0]),17)<<endl; cout<<binsearch(a,sizeof(a)/sizeof(a[0]),18)<<endl; cout<<binsearch(a,sizeof(a)/sizeof(a[0]),19)<<endl; cout<<binsearch(a,sizeof(a)/sizeof(a[0]),20)<<endl; return 0;} 123456789101112131415运行结果:3-10123456789-1