0% found this document useful (0 votes)
3 views3 pages

1. Binary and Linear Search

The document contains a C program that implements binary and linear search algorithms. It includes functions for sorting an array, performing binary and linear searches, and measuring the time taken for each search. The program prompts the user to input the size of the array and allows them to choose between the two search methods.

Uploaded by

rsviniba96
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

1. Binary and Linear Search

The document contains a C program that implements binary and linear search algorithms. It includes functions for sorting an array, performing binary and linear searches, and measuring the time taken for each search. The program prompts the user to input the size of the array and allows them to choose between the two search methods.

Uploaded by

rsviniba96
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

BINARY AND LINEAR SEARCH

Program:
#include<stdio.h>
#include<conio.h>
#include<time.h>
int binary(int item, int a[], int low, int high)
{
int mid;
mid=(low+high)/2;
delay(10);
if(low>high)
return 0;
if(a[mid]==item)
return mid+1;
else if(a[mid]>item)
return binary(item,a,low,mid-1);
else
return binary(item,a,mid+1,high);
}
int linear(int item, int n, int a[])
{
int i;
for(i=0;i<n;i++)
{
delay(1);
if(a[i]==item)
return i+1;
}
return 0;
}
void sort(int a[],int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
int main()
{
int a[10000],n,pos,item,i,opt;
clock_t start,end;
double time;
clrscr();
printf("enter the array size:");
scanf("%d",&n);
printf("\n Elements are: \n");
for(i=0;i<n;i++)
{
a[i]=(int)rand()%1000;
printf("%d\t", a[i]);
}
for(;;)
{
printf("\n 1. Binary Search \n 2. Linear Search \n 3. Exit");
printf("\n enter your Option:");
scanf("%d",&opt);
switch(opt)
{
case 1:
sort(a,n);
printf("\n Sorted list: \n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("Enter the key element:");
scanf("%d",&item);
start=clock();
pos=binary(item,a,0,n-1);
end=clock();
break;
case 2:
printf("Enter the Element to be searched:\n");
scanf("%d",&item);
start=clock();
pos=linear(item,n,a);
end=clock();
break;
default :
exit(0);
}
if(pos==0)
printf("Item not found\n");
else
printf("\n Item found at the position %d",pos);
time=(end-start)/CLK_TCK;
printf("\n Time taken = %f", time);
}
}

You might also like