二分查找(折半查找)
时间复杂度。这是一种很有效的查找方法,但是要求原始数组是有顺序的。
#include<iostream>
#include<algorithm>
using namespace std;
int binary_find(const int list[],const int& n,const int& val){
if(n <= 0) return -1;
int new_index ,low_index = 0,high_index = n-1;
while(low_index <= high_index){//这个判断条件可以只用于n = 1的情况
new_index = (low_index+high_index)/2;
if(list[new_index] == val){
return new_index;
}
else if(list[new_index] < val){
low_index = new_index+1;//这一步很关键,我第一次写的是 low_index = new_index;
}
else{
high_index = new_index-1;
}
}
return -1;
}
int main(){
int array[20];
for(int i = 0; i < 20; i++){
array[i] = rand()%100;
}
sort(array,array+20);