无法在降序数组中找到元素的位置(二进制搜索)

时间:2017-11-20 11:03:41

标签: arrays binary-search

我认为逻辑完全正常但我不知道为什么代码不会使用二进制搜索返回降序数组中给定元素的位置。

#define n 9
bool found = false;
int binarysearch(int array[n],int element){
int start = 0;
int end = n-1;
int mid;
while(start<=end && !(found)){
mid = start + end / 2;
if(element==array[mid])
found=true;
else if(element<array[mid]) {
start = mid + 1;
else
end = mid - 1;
}
if(found)
return mid;
else
return -1;
}
int main (){
int array[n]={10,9,8,7,6,5,4,3,2};
cout << "Enter the element you want to find the position in the array " << endl;
int x;
cin >> x;
int index = binarysearch(array,x);
if(index!=-1)
cout << index << endl;
else
cout << "index not found"<<endl;

所以每当我输入元素时结果都是空的。

0 个答案:

没有答案