BINARY SEARCH

Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you have narrowed down the possible locations to just one.

Process of Binary Search

1. Start with the middle number : is it bigger or smaller than our target number? Since the array is sorted, this tells us if the target would be in the left half or the right half of our array.

2. We have effectively divided the problem in half. We can "rule out" the whole half of the array that we know does not contain the target number.

3. Repeat the same approach (of starting in the middle) on the new half-size problem. Then do it again and again, until we either find the number or "rule out" the whole set. Binary Search Programming

 #include //Global array declaration int array[]={10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; //Global function declaration int BinarySearch(int list[],int value); void main() { int number, retn; printf("\n Enter the number you want to search..."); scanf("%d",&number); retn=BinarySearch(array,number); if(retn == 0) printf("\n Number not found"); else printf("\n Number found"); } int BinarySearch(int list[],int value) { int low=0, mid, high, count=0; high = (sizeof(array) / sizeof(int)) - 1; while(low <= high) { mid = (low + high) / 2; if(list[mid] == value) { count = 1; break; } else if(list[mid] < value) low = mid + 1; else if(list[mid] > value) high = mid - 1; } return count; }

QuestionSolves.com is an educational website that helps worldwide students in solving computer education related queries.

Also, different software like Visual Studio, SQL Server, Oracle etc. are available to download in different versions.

Moreover, QuestionSolves.com provides solutions to your questions and assignments also.

MORE TOPIC

WHAT WE DO

 Follow Us 