Binary Search Algorithm

#include<stdio.h>

#include<conio.h>

int BinarySearch(int [],int,int,int);

int a[100],i,n,key,flag,l,r,m;

void main(){

printf("Enter array size: ");

scanf("%d",&n);

printf("Enter array elements (in ascending order): ");

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

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

printf("Enter value to be searched: ");

scanf("%d",&key);

flag=BinarySearch(a,0,n-1,key);

if(flag==0)

printf("%d is not found.",key);

else

printf("%d is found at %d position",key,flag+1);

getch();

}


int BinarySearch(int a[],int l,int r,int key){

while(l<=r){

m=(l+r)/2;

if(key==a[m])

return m;

else if(key<a[m])

r=m-1;

else

l=m+1;

}

return 0;

// flag=0;

// if(l<=r){

// m=(l+r)/2;

// if(key==a[m])

// return flag=m;

// else if(key<a[m])

// BinarySearch(a,l,m-1,key); // recursion

// else

// BinarySearch(a,m+1,r,key); // recursion

// }

// else

// return flag;

}




No comments:

Post a Comment