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, 9, 7, 2, 4, 6}, Size = 0; // Will update size in main
- // Get the first transition index
- int findTransition1() {
- 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;
- }
- // Get the second transition index
- int findTransition2() {
- 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 TriSorted array
- int triSortedArraySearch(int x) {
- int transition1 = findTransition1(), transition2 = findTransition2();
- cout<<"Transition Indices: "<<transition1<<" "<<transition2<<endl;
- // Search in the increasing part 1
- int result = increasingBinarySearch(0, transition1-1, x);
- if (result != -1)
- return result ;
- // Search in the decreasing part
- result = decreasingBinarySearch(transition1, transition2-1, x);
- if(result != -1)
- return result;
- // Search in the increasing part 2
- result = increasingBinarySearch(transition2, Size-1, x);
- return result;
- }
- int main() {
- Size = sizeof(A) / sizeof(A[0]);
- int x = 9;
- int result = triSortedArraySearch(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