-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Search.cpp
More file actions
70 lines (61 loc) · 1.29 KB
/
Binary_Search.cpp
File metadata and controls
70 lines (61 loc) · 1.29 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
///Time Complexity: O(log(n)) for the average case
/*
Auther : Abdullah Al Masum
*/
#include <bits/stdc++.h>
using namespace std;
#define MAXX 10000000
int Arr[MAXX];
void printArray(int A[], int N)
{
for (int i = 0; i < N; i++)
{
cout << A[i] << " ";
}
cout << endl;
}
void BinarySearch(int A[], int size, int findValue)
{
sort(A, A + size);
cout << "sorted array: ";
printArray(A, size);
int low = 0;
int high = size - 1;
while (low < high)
{
int mid = (low + high) / 2;
if (findValue == A[mid])
{
cout << "found value at :" << mid << " index" << endl;
break;
}
else if (findValue > A[mid])
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
}
int main()
{
//takeInput();
cout << "Array must be sorted,otherwise my programme will automatically sort your list Then find location" << endl;
int size, findValue;
cin >> size;
for (int i = 0; i < size; i++)
{
cin >> Arr[i];
}
cin >> findValue;
BinarySearch(Arr, size, findValue);
// cout << "Here array is started from 0 index" << endl;
// printArray(Arr, size);
return 0;
}
// Input for Linear BinaryarSearch
// 5
// 2 4 4 5 6
// 4