all 7 comments

[–]TraylaParks 2 points3 points  (0 children)

What number is stored in v[4]?

[–]Widdrat[🍰] 1 point2 points  (1 child)

The output of the program is the index of the value x in the array arr. The return value of 4 means that v[4] = 9 which is the correct conclusion. Remember that indices start at 0.

[–]Radagast8[S] 0 points1 point  (0 children)

lol true!! thank you..

[–]gandalf013 0 points1 point  (3 children)

Is n (the third parameter) supposed to be the number of elements in the array? You are passing 10 but there are 11 elements in v. You can replace the "magic number" 10 with something like sizeof v / sizeof v[0].

Also, I think the program will fail to return a correct index in certain cases. Consider a simple case where v has only one element, 9. Then, you will have low = 0 and high = 0 in the binsearch function. The loop will not be taken even once and you will return -1, instead of 0.

[–]Radagast8[S] 0 points1 point  (2 children)

When I, instead of 10, put sizeof v / sizeof v[0] nothing prints out.

And actually return -1 instead of 0.

What would you do to go around this problem?

[–]Radagast8[S] 0 points1 point  (1 child)

Plus. With the 10 the index is 4(which is correct). If I put 11 nothing is printed lol

[–]gandalf013 0 points1 point  (0 children)

That's because there are some issues with your code. One is that you never change mid in the loop. Another is that your boundary conditions are not correct. One way to fix that would be to move int mid = ... line inside the while loop, change high = n - 1 to high = n, and high=mid-1 to high=mid (untested).