ADVANCED DATA STRUCTURES PROGRAM • LEVEL 13 — ADVANCED SEARCHING

Search a Rotated Sorted Array

Learn how to search a rotated sorted array using a clear C program.

IntermediateBinary searchSearch boundaries

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Index = 4

COMPLETE C PROGRAM

Complete C implementation

ads-search-rotated-sorted-array.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int values[] = {4, 5, 6, 7, 0, 1, 2}, target = 0, low = 0, high = 6;
    while (low <= high) {
        int middle = low + (high - low) / 2;
        if (values[middle] == target) { printf("Index = %d\n", middle); break; }
        if (values[low] <= values[middle]) { if (values[low] <= target && target < values[middle]) high = middle - 1; else low = middle + 1; }
        else { if (values[middle] < target && target <= values[high]) low = middle + 1; else high = middle - 1; }
    }
    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

Index = 4
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Identify the sorted half at every step and retain only the half that can contain the target.
  3. Display the computed result.

Identify the sorted half at every step and retain only the half that can contain the target.

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.