Professional Documents
Culture Documents
Question 1: The following function is the code for binary search, but some of the code is wrong. Correct the
code so the function starts working as it is intended.
Line Code Corrected code
1 public static int binSearch(int[] a, int value) {
2 int low = 0;
3 int high = a.length-1;
4 while (low <= high) {
5 int mid = low + high;
6 if (value == a[mid])
7 return low;
8 else if (value < a[mid])
9 high = mid + 1;
10 Else
11 low = mid - 1;
12 }
return -1; //this only happens if not found
}
Question 2 For a given array, you wish to find the value 118 using Linear and Binary search algorithms.
Index 0 1 2 3 4 5 6 7 8
Value 2 6 19 27 33 37 38 41 118
1. Complete the table by writing the values of low, high and mid to find the value 118 using binary search.
2. Write the number of steps it would take using linear search and the number of steps it would take using
binary search algorithms when finding the value 118 in the array.