Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add: recursion problem:: peak in mountain array and pivot in sorted rotated array #179

Merged
merged 2 commits into from
Nov 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions C++/recursion/peak_in_mountain_array.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#include <iostream>
#include <vector>
using namespace std;

int findPeak(const vector<int>& arr, int low, int high) {
int mid = low + (high - low) / 2;

// Check if mid is the peak
if ((mid == 0 || arr[mid] > arr[mid - 1]) && (mid == arr.size() - 1 || arr[mid] > arr[mid + 1])) {
return arr[mid];
}

// If mid is in the ascending part, move right
if (mid < arr.size() - 1 && arr[mid] < arr[mid + 1]) {
return findPeak(arr, mid + 1, high);
} else {
// Move left otherwise
return findPeak(arr, low, mid - 1);
}
}

int main() {
vector<int> arr = {1, 3, 8, 12, 4, 2};
cout << "Peak element: " << findPeak(arr, 0, arr.size() - 1) << endl;
return 0;
}
34 changes: 34 additions & 0 deletions C++/recursion/pivot_in_sorted_rotated_array.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#include <iostream>
#include <vector>
using namespace std;

int findPivot(const vector<int>& arr, int low, int high) {
// Base case: if only one element left, it's the pivot
if (low == high) {
return low;
}

int mid = low + (high - low) / 2;

// Check if mid is the pivot
if (mid < high && arr[mid] > arr[mid + 1]) {
return mid + 1;
}
if (mid > low && arr[mid] < arr[mid - 1]) {
return mid;
}

// Decide to search in the left or right half
if (arr[low] >= arr[mid]) {
return findPivot(arr, low, mid - 1);
} else {
return findPivot(arr, mid + 1, high);
}
}

int main() {
vector<int> arr = {4, 5, 6, 7, 0, 1, 2};
int pivotIndex = findPivot(arr, 0, arr.size() - 1);
cout << "Pivot element: " << arr[pivotIndex] << " at index " << pivotIndex << endl;
return 0;
}