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.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Peak = 20 at index 2
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Peak = 20 at index 2
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Follow an ascending slope because at least one peak exists in that direction.
- 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.
