You are on page 1of 1

Homework 1

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; Int mid = ( low + hight)/2;
6 if (value == a[mid])

7 return low; Return mid;


8 else if (value < a[mid])

9 high = mid + 1; High = mid-1;


10 Else

11 low = mid - 1; 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.
1. 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.
index 0 1 2 3 4 5 6 7 8
value 2 6 19 27 33 37 38 41 118

Linear Search number of steps taken: 9


Binary Search number of steps taken: 4

2. Deduce the oder of complexity for each algorithm.

Linear Search algorithm: O( n )


Binary Search algorithm: O( log 2n)

You might also like