#include <iostream>
using namespace std;
int pivotSearch (int arr[],int n) {
int start = 0;
int end = n-1;
int mid = start + (end-start)/2;
while (start < end) {
if (arr[mid] >= arr[0]) {
start = mid + 1;
}
else {
end = mid;
}
mid = start + (end-start)/2;
}
return end;
}
int binarySearch(int arr[],int n,int s,int e,int key) {
int start = s;
int end = e;
int mid = start + (end-start)/2;
while (start <= end){
if (arr[mid] == key) {
return mid;
}
else if (arr[mid] > key) {
end = mid - 1;
}
else {
start = mid + 1;
}
mid = start + (end-start)/2;
}
return -1;
}
int main() {
int arr[6] = {3,8,10,0,1,2};
int ans = pivotSearch(arr,6);
cout << "the pivot is at : "<< ans << endl;
if (2>=arr[ans]&&2<=arr[5]) {
cout << "the element is present in the array at index :" << binarySearch(arr,6,ans,5,2);
}
else {
cout << "the element is present in the array at index :" << binarySearch(arr,6,0,ans-1,2);
}
return 0;
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter