-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3findInSortedRoatated.cpp
More file actions
78 lines (70 loc) · 1.65 KB
/
3findInSortedRoatated.cpp
File metadata and controls
78 lines (70 loc) · 1.65 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
using namespace std;
#define MAX 50
/*
* *
* Binary Search
* */
int binarySearch(int local_arr[], int low, int high, int key)
{
if (high < low)
return -1;
int mid = (low + high) / 2;
if (local_arr[mid] == key)
return mid;
if (local_arr[mid] > key)
return binarySearch(local_arr, low, mid - 1, key);
return binarySearch(local_arr, mid + 1, high, key);
}
int findPivot(int local_arr[], int start, int end)
{
//BAse cases
if (end < start)
return -1;
if (start == end)
return start;
int mid = (start + end) / 2; /*Or "low+(high-low)/2" */
if (end > mid && local_arr[mid] > local_arr[mid + 1])
return mid;
if (mid > start && local_arr[mid - 1] > local_arr[mid])
return mid - 1;
if (local_arr[start] == local_arr[mid])
return findPivot(local_arr, start, mid - 1);
return findPivot(local_arr, mid + 1, end);
;
}
int findElement(int local_arr[], int end, int key)
{
int pivot = findPivot(local_arr, 0, end - 1);
/*
* Not find pivot
* then array is not rotated at all
*
* */
if (pivot == -1)
return binarySearch(local_arr, 0, end - 1, key);
/*
* If we found then first compare with pivot then search into
* two subarrays around pivot
*
* */
if (local_arr[pivot] == key)
return pivot;
if (local_arr[0] <= key)
return binarySearch(local_arr, 0, pivot - 1, key);
return binarySearch(local_arr, pivot + 1, end - 1, key);
}
int main()
{
int n, arr[MAX], d;
cout << "Enter Number of Elements you want in an array:";
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << "\nEnter Element you want to search:";
cin >> d;
int pos = findElement(arr, n, d);
cout << "Found at :" << pos;
}