C PROGRAM FOR BOTH BINARY AND LINEAR SEARCH
#include<stdio.h>
#define
n 10
int
bRecSear(int arr[], int data, int first, int last);
int
main()
{
int
a[n],i,v,pos=-1,f=0,l,mid;
printf("Enter
the elements of the array:\n");
for(i=0;i<n;
i++)
scanf("%d",&a[i]);
printf("How
do you want to search??\n1.Linear Search\t2.Binary Search:- ");
scanf("%d",&i);
printf("Enter
value to search in array:- ");
scanf("%d",&v);
if(i==1)
{
for(i=0;i<n;i++)
if(a[i]==v)
pos=i;
}
else
if(i==2)
{
printf("\nHw
do you want to search?\t1.By Itertion\t2.By Recursion:-");
scanf("%d",
&i);
if(i==1)
{
l=n-1;
mid
=(f+l)/2;
while
(f<=l)
{
if
(a[mid]<v )
f=mid+1;
else
if (a[mid]==v)
{
pos=f;
break;
}
else
l
= mid - 1;
mid
= (f+l)/2;
}
}
if(i==2)
{
pos=bRecSear(a,v,0,9);
}
}
if(pos==-1)
printf("\nElement
not found");
else
printf("\nElement
at position:\t%d",pos+1);
return
0;
}
int
bRecSear(int arr[], int data, int first, int last)
{
int
mid=(first+last)/2, pos=-1;
if(first<=last)
{
if(arr[mid]==data)
{
pos=mid;
}
else
if(arr[mid]<data)
{
first=mid+1;
pos=bRecSear(arr,
data, first, last);
}
else
{
last=mid-1;
pos=bRecSear(arr,
data, first, last);
}
}
return
pos;
}
OUTPUT
In this program coding is done in the ubuntu software .It is basically used for student to use linux type operating system.Programmers can learn linux type operating system through this programs.
No comments:
Post a Comment