Cannot find the position of an element inside a descending order array using binary search. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Cannot find the position of an element inside a descending order array using binary search.

Here is the code: #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 } The logic is i think okay but i guess sth is wrong with the code since it doesnt return the index or the position of a given element. Any advice would be appreciated!

20th Nov 2017, 3:15 PM
Emanuel Dajti
Emanuel Dajti - avatar
1 Answer
- 1
You are doing "mid = start + end / 2", while you probably want to do "mid = (start + end) / 2". Also, I have one advice for you -> use half-open intervals in binary search, the code will be simpler, but it is entirely on you :)
9th Dec 2017, 8:12 PM
Daniel Oravec
Daniel Oravec - avatar