Monday, 29 July 2013

Algorithm and program for Binary Search.

Binary search or half-interval search algorithm compares the
 element to be search(i.e key) with the middle element of the array. 
If the key is matched with the middle element ,it returns its 
position.and if not it divides the array into sub array according to 
the value of key. 
If the key value is greater than the value of middle element then 
the it will search the key from middle to right. 
If the key value is less than the value of middle element then the it 
will search the key from middle to left.
 It will repeat this action until no further division are possible or 
until the key matches with any of the element in array.
    Binary search  Binary search 
/*....binary search program ......*/
#include <stdio.h>
void main()
{ int arr[20]; int i, low, mid, high, key, size; printf("Enter the size of an array\n"); scanf("%d", &size); printf("Enter the elements\n"); for(i = 0; i < size; i++) { scanf("%d", &arr[i]); } printf("Enter the element to be search according to binary search\n"); scanf("%d", &key); /*Binary search */ low = 0; high = (size - 1); while(low <= high) { mid = (low + high)/2; if(key == arr[mid]) { printf("element found at %d position \n",mid+1); return; } if(key < table[mid]) high = mid - 1; else low = mid + 1; } printf("element not found\n");
getch(); } Binary search  Binary search  Binary search  Binary search 
 Output
Enter the size of an array 5 Enter the array elements 12 36 45 78 99 Enter the key 45 element found at 3 position

0 comments:

Post a Comment