-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary search.cpp
More file actions
101 lines (101 loc) · 1.76 KB
/
binary search.cpp
File metadata and controls
101 lines (101 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*first program*/
#include<iostream.h>
#include<dos.h>
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int binsearch(int [],int,int,int);
void sort(int [],int);
int linsearch(int [],int,int,int);
void main()
{
int a[2000],i,n,key,ans,choice;
clock_t start,end;
clrscr();
cout<<"enter the no. of elements \n";
cin>>n;
for(i=0;i<n;i++)
{
a[i]=rand()%100;
cout<<a[i]<<"\t";
}
cout<<"\n";
cout<<"enter the key to be searched\n";
cin>>key;
for(i=0;i<n-1;i++)
{
cout<<a[i];
cout<<"\t";
}
cout<<"\n";
cout<<"enter the type of search to be performed\n";
cout<<"1.binary,2.linear\n";
cin>>choice;
switch(choice)
{
case 1:sort(a,n);
for(i=0;i<n;i++)
cout<<a[i]<<"\t";
start=clock();
ans=binsearch(a,0,n-1,key);
if(ans==-1)
cout<<"not found\n";
else cout<<"found\n";
end=clock();
cout<<"the time was:\n"<<(end-start)/CLK_TCK;
getch();
break;
case 2:start=clock();
ans=linsearch(a,0,n-1,key);
if(ans==-1)
cout<<"key not found\n";
else
cout<<"key found\n";
end=clock();
cout<<"the time was:\n"<<(end-start)/CLK_TCK;
getch();
break;
default:exit(0);
}
}
int binsearch(int a[],int low,int high,int key)
{
delay(100);
int mid;
if(low>high)
return -1;
mid=(low+high)/2;
if(key==a[mid])
return 0;
else if(key<a[mid])
return binsearch(a,low,mid-1,key);
else
return binsearch(a,mid+1,high,key);
}
int linsearch(int a[],int i,int high,int key)
{
delay(100);
if(i>high)
return -1;
if(key==a[i])
return 0;
else
return linsearch(a,i+1,high,key);
}
void sort(int a[],int n)
{
int temp,i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j+1]<a[j])
{
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
}