File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Time complexity: O(log n)
3
+ Contributor: Deepanshu Jindal(https://github.com/ultimatecoder2)
4
+ */
5
+
6
+ #include < bits/stdc++.h>
7
+ using namespace std ;
8
+
9
+ int BinarySearch (int arr[],int low,int high,int el)
10
+ {
11
+ if (low>high)
12
+ {
13
+ return -1 ;
14
+ }
15
+
16
+ int mid = (low+high)/2 ;
17
+ if (arr[mid] == el)
18
+ {
19
+ return mid;
20
+ }
21
+ if (arr[mid]<el)
22
+ {
23
+ return BinarySearch (arr,mid+1 ,high,el);
24
+ }
25
+ if (arr[mid]>el)
26
+ {
27
+ return BinarySearch (arr,low,mid-1 ,el);
28
+ }
29
+
30
+ }
31
+ int main ()
32
+ {
33
+ int n;
34
+ cout<<" Enter Size of Array" <<endl;
35
+ cin>>n;
36
+ cout<<" Enter the elements of array" <<endl;
37
+ int arr[n];
38
+ for (int i=0 ;i<n;i++)
39
+ cin>>arr[i];
40
+ cout<<" Enter the element that you want to find" <<endl;
41
+ int el;
42
+ cin>>el;
43
+ int index =BinarySearch (arr,0 ,n-1 ,el);
44
+ if (index<0 )
45
+ cout<<" Element is not present in the array" <<endl;
46
+ else
47
+ {
48
+ cout<<" Element is present at " <<index + 1 <<" position" <<endl;
49
+ }
50
+ return 0 ;
51
+ }
You can’t perform that action at this time.
0 commit comments