Binary Search Algorithm Assignment
Binary Search Algorithm Assignment
On
Algorithm
1. Get the middle element; 2. if the middle element equals to the searched value, the algorithm stops; 3. otherwise, two cases are possible: o Searched value is less, than the middle element. In this case, go to the step 1 for the part of the array, before middle element. o Searched value is greater, than the middle element. In this case, go to the step 1 for the part of the array, after middle element. We should define when iterations should stop. First case is when searched element is found. Second one is when sub array has no elements. In this case, we can conclude, that searched value doesn't present in the array.
Example
Find 6 in {-1, 5, 6, 18, 19, 25, 46, 78, 102, 114}. Step 1 (middle element is 19 > 6): Step 2 (middle element is 5 < 6): Step 3 (middle element is 6 == 6): -1 5 6 18
19
25 46 78 102 114
Pseudo-code
procedure bin search(x: integer, a 1,a2,.an: increasing order integer) a=1 ( a is the left endpoint of search interval) b= n( b is the right endpoint of search interval) while ( a<b) begin m = (a+b)/2 if x>am then i=m+1 else j=m end if x=ai then location = i else location = 0
Code in C
main() { int c, first, last, middle, n, search, array[100]; printf("Enter number of elements\n"); scanf("%d",&n); printf("Enter %d integers\n", n); for ( c = 0 ; c < n ; c++ ) scanf("%d",&array[c]); printf("Enter value to find\n"); scanf("%d",&search); first = 0; last = n - 1; middle = (first+last)/2;
while( first <= last ) { if ( array[middle] < search ) first = middle + 1; else if ( array[middle] = = search ) { printf("%d found at location %d.\n", search, middle+1); break; } else last = middle - 1; middle = (first + last)/2; } if ( first > last ) printf("Not found! %d is not present in the list.\n", search); return 0; }
Explanation This algorithm first assigns the initial term of the given sequence a1 to the variable max. The for loop is used to successively examine terms of the sequence. If a term is greater than the current value of max, it is assigned to the new value of max. In this way maximum value will be calculated from the given sequence.