Binary Search:
- Binary search can be applied to only sorted array.
- In binary search, we find the mid location and compare with searching element.
- If the searching element less than mid location element, search goes to left side.
- If the searching element greater than mid location, search goes to right side.

int main() { int a[10],m,i,n,k,low,high, found=0; printf(“Enter the size of array : “); scanf(“%d”,&n); printf(“Enter %d elements \n”,n); for(i=0;i<n;i++) { scanf(“%d”,&a[i]); } low=0; high=n-1; printf(“Enter the key value : “); scanf(“%d”,&k); while(low<=high) { m=(low+high)/2; if(k<a[m]) { high=m-1; } else if(k>a[m]) { low=m+1; } else if(k==a[m]) { printf(“Element found @ loc : %d\n”,m); found=1; break; } } if(!found) { printf(“Not found\n”); } return 0; } |