Binary Search in C programming language

If we look at the questions viz. How do we search for a person’s telephone number? If we know only the person’s name. and How difficult is this? Similarly How do we search for a person’s name? If we know only the person’s telephone number. and Why is this more difficult? similarly How do we search for a student blue book, when blue books are unsorted? AND when blue books are sorted?
Here what we can notice is Searching will be easier if the list is sorted. The technique what we use in searching of key element in sorted list is Binary Search. It works only on Sorted Elements.
How does it work?
It finds the middle element in the complete list of sorted elements then Compares the key element with middle element and STOPS if middle element is KEY and declare Successful Search. If KEY is less than middle element then it search in the lower half of the sorted list in the same way and If KEY is greater than middle element it search in the higher half of the sorted list in the same way and finally If Array exhaust it STOPS and declare Unsuccessful search.\

Ex: Program to find given key element in an array of n integer elements using Binary Search

int main ()
{ int a[50], n, key, low, high, mid, i, flag = 0;
printf(“\n\tEnter the number of elements: “);
scanf(“%d”, &n); /* 1 = n = 50*/
printf(“\n\tEnter %d Elements of an array in Sorted Order: “, n);
for ( i = 0; i < n; i++ )
scanf(“%d”, &a[i]);
printf(“\n\tEnter the Key element to be Searched: “);
scanf(“%d”, &key);
low = 0; high = n – 1;
while(low <= high)
{
mid = (low + high) / 2;
if(key == a[mid]) flag = 1;
else if(key > a[mid]) low = mid + 1;
else high = mid – 1;
}
if( flag == 1) printf(“Successful Search - Key found ”);
else printf(“Unsuccessful Search - Key NOT found”);
return 0;
}
Binary Search in C programming language Binary Search in C programming language Reviewed by Unknown on 08:15 Rating: 5

No comments:

Powered by Blogger.