What if you could find the tallest hill without climbing every single one?
Why Find Peak Element Using Binary Search in DSA C++?
Imagine you have a long list of numbers representing heights of hills along a trail. You want to find a hill that is taller than its neighbors, a peak. If you check each hill one by one from start to end, it will take a lot of time, especially if the trail is very long.
Checking each hill manually means walking the entire trail step by step, which is slow and tiring. Also, if you miss comparing a hill with its neighbors carefully, you might pick a wrong hill that is not really a peak.
Using binary search, you can quickly jump to the middle hill and decide which half of the trail to explore next based on the heights. This way, you find a peak much faster without checking every hill.
int findPeak(int arr[], int n) {
for (int i = 0; i < n; i++) {
if ((i == 0 || arr[i] >= arr[i-1]) && (i == n-1 || arr[i] >= arr[i+1]))
return i;
}
return -1;
}int findPeak(int arr[], int n) {
int left = 0, right = n - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid] < arr[mid + 1])
left = mid + 1;
else
right = mid;
}
return left;
}This method lets you find a peak element in a list quickly, even if the list is very large, saving time and effort.
Finding a peak is like quickly spotting the tallest building in a city skyline by looking at only a few buildings instead of checking every single one.
Manual search checks every element, which is slow.
Binary search jumps smartly to find a peak faster.
Useful for large data where speed matters.