Fundamentals 3 min read

How to Find the Peak in a Bitonic Array Using Binary Search

This article presents a JavaScript solution for locating the maximum element in a bitonic (first increasing then decreasing) array, explaining that the problem is a variant of binary search and providing a complete implementation using a binary‑search‑based algorithm.

Programmer DD
Programmer DD
Programmer DD
How to Find the Peak in a Bitonic Array Using Binary Search

Code Implementation

The following JavaScript function finds the maximum value in an array that first increases and then decreases (a bitonic array) using a binary‑search‑based approach.

Comment: This problem is essentially a variant of binary search.

function getMaxValue(arr) {
    let len = arr.length;
    // When only one element, return it
    if (len === 1) return arr[0];
    // When the array is strictly decreasing, return first element
    if (arr[0] > arr[1]) return arr[0];
    // When the array is strictly increasing, return last element
    if (arr[len - 1] > arr[len - 2]) return arr[len - 1];
    // Process arrays with both increasing and decreasing parts (at least 3 elements)
    let left = 0,
        right = arr.length - 1;
    while (left < right) {
        let mid = Math.floor((left + right) / 2);
        // Check if arr[mid] is the maximum
        if (mid !== 0 && arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1])
            return arr[mid];
        // Determine whether mid is in the increasing part or decreasing part
        if (mid === 0 || arr[mid] > arr[mid - 1]) {
            // increasing part
            left = mid + 1;
        } else if (arr[mid] < arr[mid - 1]) {
            // decreasing part
            right = mid - 1;
        }
    }
    return arr[left];
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

algorithmJavaScriptBinary Searchinterview questionbitonic array
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.