ADVANCED DATA STRUCTURES PROGRAM • LEVEL 13 — ADVANCED SEARCHING

Find a Peak Element by Binary Search

Learn how to find a peak element by binary search using a clear C program.

IntermediateBinary searchSearch boundaries

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Peak = 20 at index 2

COMPLETE C PROGRAM

Complete C implementation

ads-find-peak-element.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int values[] = {1, 3, 20, 4, 1, 0}, low = 0, high = 5;
    while (low < high) { int middle = low + (high - low) / 2; if (values[middle] < values[middle + 1]) low = middle + 1; else high = middle; }
    printf("Peak = %d at index %d\n", values[low], low); return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Peak = 20 at index 2
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Follow an ascending slope because at least one peak exists in that direction.
  3. Display the computed result.

Follow an ascending slope because at least one peak exists in that direction.

EFFICIENCY

Time and space complexity

Time complexity

O(log n)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.