-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlinbin.cpp
More file actions
95 lines (76 loc) · 1.43 KB
/
Copy pathlinbin.cpp
File metadata and controls
95 lines (76 loc) · 1.43 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
#include <iostream>
using namespace std;
void linearSear(int [], int , int);
void binarySear(int [], int ,int );
void populateNum(int [], int);
int main()
{
int size;
char input;
int userValue;
do
{
cout << "Enter the size of array : "<<endl;
cin >> size;
int a[size];
cout << "Enter a element between 1 and "<<size<<endl;
cin >> userValue;
populateNum(a, size);
linearSear(a , size, userValue);
binarySear(a, size, userValue);
cout<<"Enter 'y' if you want to run this again :"<<endl;
cin >> input;
// cin.get(input);
cin.sync();
}while(input == 'y');
return 0;
}
void linearSear(int array[], int size, int Uval)
{
int count = 0;
for(int i = 0; i < size; i++)
{
count++;
if(Uval == array[i])
{
break;
}
}
cout << "The Linear Search comparisons: " << count <<"\n"<<endl;
cout << "The Linear Search cost is : " << count << "\n"<<endl;
}
void binarySear(int array[], int size, int Uval)
{
int low = 0;
int high = size - 1;
int mid;
int count = 0;
int cost = 0;
while(low <= high)
{
mid = (low + high)/2;
count++;
cost += 3;
if(Uval == array[mid])
{
break;
}
else if(Uval > array[mid])
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
cout << "The Binary Search comparisons : " << count << "\n"<<endl;
cout << "The Binary search cost is : " << cost <<"\n"<<endl;
}
void populateNum(int array[], int size)
{
for(int i = 1; i <= size; i++)
{
array[i-1] = i;
}
}