binary search in c

A binary search locates an item in a sorted array by repeatedly dividing the search interval in half. The initial interval includes the entire array. If the value of the search key is less than the item in the middle of the interval, then the next interval will be the lower half of the current interval. If the value of the search key is greater than the middle item, then the next interval will be the upper half. The search process repeats until the item is found or the search interval is empty. Binary Search is an O(log n) algorithm, which is more efficient than a linear search for large arrays

PROGRAM:

#include<stdio.h>

int main(){

int a[10],i,n,m,c=0,l,u,mid;

printf(“Enter the size of an array: “);

scanf(“%d”,&n);

printf(“Enter the elements in ascending order: “);

for(i=0;i<n;i++){

scanf(“%d”,&a[i]);

}

printf(“Enter the number to be search: “);

scanf(“%d”,&m);

l=0,u=n-1;

while(l<=u){

mid=(l+u)/2;

if(m==a[mid]){

c=1;

break;

}

else if(m<a[mid]){

u=mid-1;

}

else

l=mid+1;

}

if(c==0)

printf(“The number is not found.”);

else

printf(“The number is found.”);

return 0;

}

OUTPUT:

Enter the size of an array: 5

Enter the elements in ascending order: 4 7 8 11 21

Enter the number to be search: 11

The number is found.

 related links….

Latest posts by admin (see all)

More in sem1
linear search in c

linear search in c PROGRAM: #include<stdio.h> int main(){ int a[10],i,n,m,c=0; printf("Enter the size of an array: "); scanf("%d",&n); printf("Enter the...

Close