Binary Search And Linear Search
//Binary search in c .............
#include<stdio.h>
int main()
{
int i,first,value,last,middle,n,a[7];
printf("Enter your array's size:\n");
scanf("%d",&n);
first=0;
last=n-1;
middle=(first+last)/2;
printf("Enter your array:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter search value:\n");
scanf("%d",&value);
while(first<=last)
{
if(a[middle]<value)
{
first=middle+1;
}
else if(a[middle]==value)
{
printf("%d is founded",value);
break;
}
else
last=middle-1;
middle=(first+last)/2;
}
if(first>last)
printf("Not founded");
}
//Linear Search in C......
#include<stdio.h>
int linear(int b[],int x,int value )
{
int position=-1;
int index=0;
bool found=false;
while(index<x && !false)
{
if(b[index]==value)
{
found=true;
position=index;
printf("Found!!");
}
index++;
}
return position;
}
int main()
{
int a[8],i,j,v,n;
printf("Enter your array's size:\n");
scanf("%d",&n);
printf("Enter your Array:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter your search value:\n");
scanf("%d",&v);
int m;
m=linear( a,n,v);
if(m==-1)
{
printf("NOT FOUND!!");
}
else
{
printf("\nThe position is: %d\n",m+1);
}
return 0;
}
No comments