0

What is wrong in this function? Why isn't it working?

int binarySearch(int a[], int n, int num) { int low = 0, high = n - 1; int mid = (low + high)/2; while(low <= high) { if(num == a[mid]) return mid; else if(num < a[mid]) high = mid - 1; else low = mid + 1; } return -1; }

19th Dec 2016, 7:57 PM
Hrishikesh Bawane
Hrishikesh Bawane - avatar
4 Antworten
+ 4
the problem is that you are returning -1 anyway... you need to return the answer...
19th Dec 2016, 8:39 PM
S. Saeed Hosseini
S. Saeed Hosseini - avatar
+ 1
You forgot to update mid after each iteration A good solution may be move the initialization of mid to the first statement of the loop.
19th Dec 2016, 9:14 PM
R P
R P - avatar
0
Thanks alot. Updation was missing. Thanks fr the help guys
20th Dec 2016, 3:00 AM
Hrishikesh Bawane
Hrishikesh Bawane - avatar
0
You're welcome ^^
20th Dec 2016, 7:17 AM
R P
R P - avatar