**New course!**Every coder should learn

**Generative AI!**

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; }

4 Answers

+ 4

the problem is that you are returning -1 anyway...
you need to return the answer...

+ 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.

0

Thanks alot. Updation was missing. Thanks fr the help guys

0

You're welcome ^^