-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram1.cpp
More file actions
63 lines (49 loc) · 1.13 KB
/
program1.cpp
File metadata and controls
63 lines (49 loc) · 1.13 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
//Search an element in a sorted and Rotated array
#include<iostream>
using namespace std;
int binarySearch(int arr[] , int n , int key){
int s = 0;
int e = n - 1;
int mid = s + (e - s)/2;
while(s<e){
if (arr[mid] == key){
return mid;
}
if (arr[s] < arr[mid]){
if (key >= arr[s] && key <=arr[mid]){
e = mid - 1;
}
else{
s = mid + 1;
}
}
else{
if (arr[mid]<=key && arr[e]>=key){
s = mid + 1;
}
else{
e = mid - 1;
}
}
mid = s + (e - s)/2;
}
}
int main(){
int n;
cout<<"Enter the number of elements in array : ";
cin>>n;
int arr[n];
for (int i = 0;i<n;i++){
cin>>arr[i];
}
cout<<"[ ";
for(int i = 0; i<n;i++){
cout<<arr[i]<<" ,";
}
cout<<"]"<<endl;
int key;
cout<<"Enter the element which you want search : ";
cin>>key;
int ans = binarySearch(arr,n,key);
cout<<"your element in this array at index "<<ans;
}