Find the bug in this java code: public static int findfirstin_sorted(int[] arr, int x) {…
- User
Find the bug in this java code: public static int find_first_in_sorted(int[] arr, int x) { int lo = 0; int hi = arr.length;
while (lo <= hi) { int mid = (lo + hi) / 2; // check if this is floor division if (x == arr[mid] && (mid == 0 || x != arr[mid-1])) { return mid; } else if (x <= arr[mid]) { hi = mid; } else { lo = mid + 1; } } return -1; } - Assistant
The Java code you've provided for finding the first occurrence of a number
xin a sorted array has a couple of issues:-
Index out of bounds error: The variable
hiis initialized toarr.length, which is out of bounds for the array when accessingarr[mid]. Since array indices start at 0 and go up toarr.length - 1,hishould be initialized toarr.length - 1.
-