Tweet
/* Binary Search */
#include<stdio.h>
void swap(int *a,int x,int y)
{
int temp=*(a+x);
*(a+x)=*(a+y);
*(a+y)=temp;
}
void bubble_sort(int a[],int n)
{
int i,j;
for(i=0;i<n-1;i++)
for(j=0;j<n-1-i;j++)
if(a[j]>a[j+1])
swap(a,j,j+1);
}
void binary_search(int a[],int n,int x)
{
int l=0,h=n-1,mid;
int flag=0,pos;
while(l<=h)
{
mid=(l+h)/2;
if(x==a[mid])
{
pos=mid;
flag=1;
break;
}
else if(x>a[mid])
l=mid+1;
else
h=mid-1;
}
if(flag)
printf("\nSuccess !! Element found at position : %d \n",pos+1);
else
printf("\nElement is not present in the array !!! \n");
}
main()
{
int x,n,i;
printf("\nProgram to find a number using binary search : \n");
printf("Enter array capacity : ");
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
a[i]=rand()%100;
bubble_sort(a,n);
printf("\nGiven array : ");
for(i=0;i<n;i++)
printf("%4d",a[i]);
printf("\n\nEnter the element to be searched for : ");
scanf("%d",&x);
binary_search(a,n,x);
printf("\n\n\n");
}
Binary Search Programming in C
Posted by
LAHAUL SETH
~
Binary Search Programming in C
2011-11-30T12:09:00+05:30
LAHAUL SETH
Programming in C
|
Comments
Binary Search Programming in C
2011-11-30T12:09:00+05:30
LAHAUL SETH
Programming in C
|