C program to Search element using Binary Search Algorithm

(337 Views)


What is Binary Search?

Binary Search is one of the Fastest Searching Algorithm with run-time complexity of Ο(log n). Binary Search Algorithm works on Divide and Conquer principle. The only condition for this algorithm is that the Data Collection should be in sorted form. i.e All the Elements in an Array should be sorted.

How Binary Search Algorithm Works?

Binary search searches for a particular item by first comparing the middle most element of the collection. If a match occurs, then the index value of the element is returned. If the middle item is greater than the element, then the element is searched in the sub-array to the left of the middle element. Otherwise, the element is searched in the sub-array to the right of the middle element. This procedure continues on the sub-array as well until the size of the subarray reduces to zero.

Binary Search Algorithm Step by Step Explanation

Binary Search Pseudocode Explanation

Binary Search Pseudocode in C

#include<stdio.h> main() { int a[20],i,j,d,t,x,l=0,low,mid,high; printf("\nEnter the number of elements to be stored in array\n"); scanf("%d",&d); printf("Enter the numbers\n"); for(i=0;i<d;i++) scanf("%d",&a[i]); for(i=0;i<d;i++) { for(j=i+1;j<d;j++) { if(a[i]>a[j]) { t=a[i]; a[i]=a[j]; a[j]=t; } } } printf("\nThe sorted list :"); for(i=0;i<d;i++) printf("%d ",a[i]); printf("\n Enter the number to be searched\n"); scanf("%d",&x); low=0; high=d-1; while(low<=high) { mid=(low+high)/2; if(x<a[mid]) high=mid-1; else if(x>a[mid]) low=mid+1; else { if(x==a[mid]) { l++; printf("The item %d is found at location %d\n",x,mid+1); exit(0); } } } if(l==0) printf("Item not found\n"); }

Output:

Enter the number of elements to be stored in array 6 Enter the numbers 17 28 34 75 83 88 The sorted list :17 28 34 75 83 88 Enter the number to be searched 88 The item 88 is found at location 6 ...Program finished with exit code 0 Press ENTER to exit console.

The above Binary Search Algorithm first sorts the array and then searches for the item in the array.

Solution Worked 1 UpvotesUpvote

        

Solution Didn't Worked 0 DownvotesDownvote



Comments



Search