What if you could find the tallest mountain without climbing every hill?
Why Find Peak Element Using Binary Search in DSA Javascript?
Imagine you have a long list of numbers representing mountain heights along a trail. You want to find a peak, a mountain taller than its neighbors, but checking each mountain one by one is tiring and slow.
Checking each mountain manually means walking the entire trail, which takes a lot of time and effort. It's easy to make mistakes or miss the peak if you get tired or distracted.
Using binary search, you can quickly jump to the middle mountain and decide which side to explore next, cutting the search area in half each time. This way, you find a peak much faster without checking every mountain.
function findPeak(nums) {
for (let i = 0; i < nums.length; i++) {
if ((i === 0 || nums[i] > nums[i - 1]) && (i === nums.length - 1 || nums[i] > nums[i + 1])) {
return i;
}
}
return -1;
}function findPeak(nums) {
let left = 0;
let right = nums.length - 1;
while (left < right) {
let mid = Math.floor((left + right) / 2);
if (nums[mid] < nums[mid + 1]) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}This method lets you find a peak element in a large list quickly and efficiently, saving time and effort.
Finding the highest point in a hiking trail map quickly without checking every single point.
Manual search checks every element, which is slow.
Binary search cuts the search area in half each step.
Efficiently finds a peak without scanning the whole list.