Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- int A[] = {1, 3, 8, 12, 4, 2}, Size = 0; // Will update size in main
- // Get the transition index
- int findTransition() {
- int left = 0, right = Size - 1;
- while (left < right) {
- int mid = left + (right - left) / 2;
- if (A[mid] > A[mid + 1]) {
- right = mid; // Move to left subarray
- } else {
- left = mid + 1; // Move to right subarray
- }
- }
- return left;
- }
- // Binary Search on increasing subarray
- int increasingBinarySearch(int left, int right, int x) {
- while (left <= right) {
- int mid = left + (right - left) / 2;
- if (A[mid] == x)
- return mid;
- if (A[mid] < x)
- left = mid + 1;
- else
- right = mid - 1;
- }
- return -1;
- }
- // Binary Search on decreasing subarray
- int decreasingBinarySearch(int left, int right, int x) {
- while (left <= right) {
- int mid = left + (right - left) / 2;
- if (A[mid] == x)
- return mid;
- if (A[mid] > x)
- left = mid + 1;
- else
- right = mid - 1;
- }
- return -1;
- }
- // Function to search x in a BiSorted array
- int biSortedArraySearch(int x) {
- int transition = findTransition();
- cout<<"Transition Index: "<<transition<<endl;
- // Search in the increasing part
- int result = increasingBinarySearch(0, transition-1, x);
- if (result != -1)
- return result;
- else
- // Search in the decrasing part
- return decreasingBinarySearch(transition, Size - 1, x);
- }
- int main() {
- Size = sizeof(A) / sizeof(A[0]);
- int x = 0;
- int result = biSortedArraySearch(x);
- if (result != -1) {
- cout << "Element " << x << " found at index " << result << endl;
- } else {
- cout << "Element " << x << " not found." << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement