-
Notifications
You must be signed in to change notification settings - Fork 0
/
31_binary_search_array.cpp
57 lines (49 loc) · 1020 Bytes
/
31_binary_search_array.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
//31. number searching in array by binary search
//complexity = O(log base2 n). it is better than linear search
#include <bits/stdc++.h>
using namespace std;
int binarySearch(int arr[], int n, int key)
{
int s = 0;
int e = n-1;
while(s<=e)
{
int m = (s+e)/2;
if(arr[m] > key)
{
e=m-1;
}
else if(arr[m] < key)
{
s = m+1;
}
else if(arr[m]==key)
{
return m;
}
}
return -1;
}
int main()
{
int arr[]={18,12,20,42,8,24,33,22};
int n = (sizeof(arr)/sizeof(arr[0]));
int temp;
int key = 20;
//sorting start
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(arr[i]>arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//sorting end
//arr[] = {8,12,18,20,22,24,33,42} -> new array
cout<< binarySearch(arr,n,key) + 1;
}