Skip to content

Commit e52bb0d

Browse files
committed
add code of search element in rotated and sorted array
1 parent 669f876 commit e52bb0d

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

a.out

-4 KB
Binary file not shown.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// https://www.geeksforgeeks.org/search-an-element-in-a-sorted-and-pivoted-array/
2+
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
int searchElement(int arr[], int n, int x){
7+
int l = 0;
8+
int r = n-1;
9+
while(l <= r){
10+
int mid = l + (r-l)/2;
11+
if(x == arr[mid])
12+
return mid;
13+
else if(arr[l] <= arr[mid]){
14+
if(x >= arr[l] && x <= arr[mid])
15+
r = mid-1;
16+
else
17+
l = mid+1;
18+
}
19+
else{
20+
if(x >= arr[mid] && x <= arr[r])
21+
l = mid+1;
22+
else
23+
r = mid-1;
24+
}
25+
}
26+
return -1;
27+
}
28+
29+
int main(){
30+
int arr[] = {4,5,6,7,0,1,2};
31+
int n = sizeof(arr)/sizeof(arr[0]);
32+
int x = 4;
33+
int res = searchElement(arr,n,x);
34+
cout << "element at index :: " << res << endl;
35+
return 0;
36+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy