120 likes | 285 Views
Binary Search. By Jee You Cheng. Algorithm:. Given a SORTED array and an input value , find the MIDDLE element of the array and compare it to the input. If they are equal, the value of middle is returned and yay , the input is found!! =D
E N D
BinarySearch By Jee You Cheng
Algorithm: • Given a SORTED array and an inputvalue, find the MIDDLE element of the array and compare it to the input. If they are equal, the value of middle is returned and yay, the input is found!! =D • If they are not equal, the array will be halved accordingly. If input is less than middle element, first half is taken and vice versa. • Within this half array, the steps above are repeated.
This process of halving the array is repeated until the input is found or further division is no longer possible. • When further division is no longer possible, this indicates that the input is not located within the array. Hence, a unique value will be returned instead.
Code: intbinarySearch(int list[], int size, int value) { int left = 0, right = (size-1), mid, index = -1, n=0; while ( (left <= right) && (index == -1)) { mid = (left + right) / 2;
if (list[mid] == value) index = mid; else if (list[mid] > value) right = mid - 1; else left = mid + 1; n++; } printf(“Number of comparisons: %d\n”, n); return index; }
Tracing…. • The 3 index variables to keep track of are left, right and mid. • Size = 10, mid = (left + right) /2 • For input = 44 : 1. left = 0, right = 9, mid = (0+9) /2 = 4
For input = 90 : 1. left = 0, right = 9, mid = (0+9) /2 = 4 2. left = 5, right = 9, mid = (5+9) /2 = 7 3. left = 8, right = 9, mid = (8+9) /2 = 8
For input = 20 : 1. left = 0, right = 9, mid = (0+9) /2 = 4 2. left = 0, right = 3, mid = (0+3) / 2 = 1 3. left = 2, right = 3, mid = (2+3) / 2 = 2
For input = 93 : 1. left = 0, right = 9, mid = (0+9) /2 = 4 2. left = 5, right = 9, mid = (5+9) /2 = 7 3. left = 8, right = 9, mid = (8+9) /2 = 8 4. left = 9, right = 9, mid = (9+9) /2 = 9