-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary Search.cpp
60 lines (52 loc) · 1.17 KB
/
Binary Search.cpp
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
#include<iostream>
using namespace std;
const int SIZE = 5;
int BinarySearch(int *Arr, int elem, int low, int high);
int binarySearch(int *Arr, int elem, int low, int high);
int main()
{
//int size =5;
// << " Enter the size of array : " << endl;
//cin >> size;
int arr[SIZE];
int n ,BS;
cout << " Enter elements of arrayin sorted order :" << endl;
for (int i = 1; i <= SIZE; ++i)
{
cin >> arr[i];
}
cout << " Enter the element you want to find " << endl;
cin >> n;
BS=BinarySearch(arr, n, 0, SIZE);
if (BS ==-1)
{
cout << " Element not found !" << endl;
}
else
cout << " The elemnt " << n << " found at " << BS << endl;
system("pause");
return 0;
}
int BinarySearch(int *Arr, int elem, int low,int high)
{
int mid;
if (low > high)
return -1;
mid = (low + high) / 2;
if (elem == Arr[mid])
return mid;
if (elem < Arr[mid])
return binarySearch(Arr, elem, low, mid - 1);
else
return binarySearch(Arr, elem, mid + 1, high);
}
int binarySearch(int *Arr, int index, int low, int high)
{
for (int i = low; i < high; ++i)
{
if (Arr[i] == index)
{
return i;
}
}
}