-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinarySearch.cpp
More file actions
110 lines (85 loc) · 1.66 KB
/
Copy pathbinarySearch.cpp
File metadata and controls
110 lines (85 loc) · 1.66 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
102
103
104
105
106
107
108
109
110
#include <iostream>
#include <array>
using namespace std;
void userInput(int [], int);
int binarySearch(int [], int, int);
void populatedNum(int[], int);
void displayElements(int [], int);
int main()
{
int size;
char input;
cout << "Enter the size of an array:"<< endl;
cin >> size;
int a[size] ;
//populatedNum(a, size);
userInput(a , size);
int userValue;
do
{
displayElements(a, size);
cout << "Enter an integer: "<< endl;
cin >> userValue;
int result = binarySearch(a, size, userValue);
{
if(result >= 0)
{
cout << "The number "<< a[result] << "is found on the " << result << "th index."<< endl;
}
else
{
cout << "The number " << userValue << "is not found "<<endl;
}
}
cout << "Enter 'y' if you want another number index: "<<endl;
cin >> input;
cin.sync();
}while(input == 'y');
return 0;
}
void userInput(int array[], int size)
{
cout << "Enter "<<size << " elements in sorted order in the array.\n\n"<<endl;
for(int i = 0; i < size; i++)
{
cout << "Enter the elements in sorted order in the array : " << endl;
cin >> array[i];
}
}
int binarySearch(int array[], int size, int searchValue)
{
int low = 0;
int high = size - 1;
int mid;
while(low <= high)
{
mid = (low + high)/2;
if(searchValue == array[mid])
{
return mid;
}
else if(searchValue > array[mid])
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
void populatedNum(int array[], int size)
{
for (int i = 1 ; i <= size ; i++)
{
array[i - 1] = i;
}
}
void displayElements(int array[], int size)
{
for(int i =0; i < size; i++)
{
cout << "The elementes enterd are :"<< array[i]<<endl;
}
}