You are on page 1of 1

Assignment 1 ( / 4 points)

Student Name: ID student:

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.

low high mid

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.

Linear Search number of steps taken:


Binary Search number of steps taken:

1. Deduce the oder of complexity for each algorithm.


Linear Search algorithm:
Binary Search algorithm:
1

You might also like