Advertisement
AnindyaBiswas

BiSortedArray

Aug 25th, 2024 (edited)
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.92 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int A[] = {1, 3, 8, 12, 4, 2}, Size = 0; // Will update size in main
  6.  
  7. // Get the transition index
  8. int findTransition() {
  9.     int left = 0, right = Size - 1;
  10.  
  11.     while (left < right) {
  12.         int mid = left + (right - left) / 2;
  13.  
  14.         if (A[mid] > A[mid + 1]) {
  15.             right = mid; // Move to left subarray
  16.         } else {
  17.             left = mid + 1; // Move to right subarray
  18.         }
  19.     }
  20.  
  21.     return left;
  22. }
  23.  
  24. // Binary Search on increasing subarray
  25. int increasingBinarySearch(int left, int right, int x) {
  26.     while (left <= right) {
  27.         int mid = left + (right - left) / 2;
  28.  
  29.         if (A[mid] == x)
  30.             return mid;
  31.         if (A[mid] < x)
  32.             left = mid + 1;
  33.         else
  34.             right = mid - 1;
  35.     }
  36.  
  37.     return -1;
  38. }
  39.  
  40. // Binary Search on decreasing subarray
  41. int decreasingBinarySearch(int left, int right, int x) {
  42.     while (left <= right) {
  43.         int mid = left + (right - left) / 2;
  44.  
  45.         if (A[mid] == x)
  46.             return mid;
  47.         if (A[mid] > x)
  48.             left = mid + 1;
  49.         else
  50.             right = mid - 1;
  51.     }
  52.  
  53.     return -1;
  54. }
  55.  
  56. // Function to search x in a BiSorted array
  57. int biSortedArraySearch(int x) {
  58.     int transition = findTransition();
  59.     cout<<"Transition Index: "<<transition<<endl;
  60.    
  61.     // Search in the increasing part
  62.     int result = increasingBinarySearch(0, transition-1, x);
  63.  
  64.     if (result != -1)
  65.         return result;
  66.     else
  67.         // Search in the decrasing part
  68.         return decreasingBinarySearch(transition, Size - 1, x);
  69. }
  70.  
  71. int main() {
  72.  
  73.     Size = sizeof(A) / sizeof(A[0]);
  74.     int x = 0;
  75.     int result = biSortedArraySearch(x);
  76.     if (result != -1) {
  77.         cout << "Element " << x << " found at index " << result << endl;
  78.     } else {
  79.         cout << "Element " << x << " not found." << endl;
  80.     }
  81.  
  82.     return 0;
  83. }
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement