Skip to content
Laviyx Learn

Try

PPS Lab · Experiment 43

Binary search

CSorting and searchingJNTUH R22 · CS108ES

Aim

To write a C program that uses a non-recursive function to search for a key value in a sorted list of integers using binary search, and prints its position or a "not found" message.

Algorithm

  1. Read n (1 to 100) and then n integers in ascending order. If any number is smaller than the one before it, print an error and stop.
  2. Read the key to search for.
  3. In the function, set low = 0 and high = n − 1.
  4. While low ≤ high, find mid = (low + high) / 2.
  5. If a[mid] equals the key, return mid. If a[mid] is less than the key, the key can only be on the right, so set low = mid + 1. Otherwise set high = mid − 1.
  6. If the loop ends, the key is not in the list: return −1.
  7. Print the position, or that the key was not found.

Program

C
#include <stdio.h>

#define MAX 100

/* Returns the index of key in the sorted array a[0..n-1], or -1 if key is not present */
int binary_search(const int a[], int n, int key) {
    int low = 0, high = n - 1;

    while (low <= high) {
        int mid = (low + high) / 2;
        if (a[mid] == key) {
            return mid;
        } else if (a[mid] < key) {
            low = mid + 1;      /* key is in the right half */
        } else {
            high = mid - 1;     /* key is in the left half */
        }
    }
    return -1;
}

int main(void) {
    int a[MAX], n, key;

    printf("Enter the number of elements (1 to %d): ", MAX);
    if (scanf("%d", &n) != 1 || n < 1 || n > MAX) {
        printf("Invalid number of elements\n");
        return 1;
    }
    printf("Enter %d integers in ascending order: ", n);
    for (int i = 0; i < n; i++) {
        if (scanf("%d", &a[i]) != 1) {
            printf("Invalid input\n");
            return 1;
        }
        if (i > 0 && a[i] < a[i - 1]) {
            printf("The list is not in ascending order\n");
            return 1;
        }
    }
    printf("Enter the key to search: ");
    if (scanf("%d", &key) != 1) {
        printf("Invalid input\n");
        return 1;
    }

    int index = binary_search(a, n, key);
    if (index == -1) {
        printf("%d is not found in the list\n", key);
    } else {
        printf("%d is found at position %d (index %d)\n", key, index + 1, index);
    }
    return 0;
}

Output

Key is in the list

Output 1
Enter the number of elements (1 to 100): 7
Enter 7 integers in ascending order: 7 12 23 34 56 78 89
Enter the key to search: 56
56 is found at position 5 (index 4)

Key is not in the list

Output 2
Enter the number of elements (1 to 100): 7
Enter 7 integers in ascending order: 7 12 23 34 56 78 89
Enter the key to search: 40
40 is not found in the list

List not sorted

Output 3
Enter the number of elements (1 to 100): 5
Enter 5 integers in ascending order: 10 30 20 40 50
The list is not in ascending order

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

How the first run finds 56 in 7 12 23 34 56 78 89 (indexes 0 to 6):

  • low = 0, high = 6, mid = 3. a[3] = 34 is less than 56, so low = 4.
  • low = 4, high = 6, mid = 5. a[5] = 78 is more than 56, so high = 4.
  • low = 4, high = 4, mid = 4. a[4] = 56. Found at index 4, which is position 5.

For 40 the search narrows down until low becomes greater than high, and the function returns −1.

Binary search gives wrong answers on an unsorted list, so the program checks the order while reading and stops if the list is not ascending.

Common mistakes

  • Using binary search on an unsorted list. It can miss a key that is present. Sort the list first, or check that it is sorted.

  • Writing while (low < high). When low equals high there is still one element to check, so the key can be missed. Use low <= high.

  • Setting low = mid or high = mid instead of mid + 1 and mid - 1. The range may then stop shrinking and the loop never ends.

  • Returning 0 for not found. 0 is a valid index, so use −1.

Viva questions

Try to answer each one aloud before you open it.

  • What is the main condition for using binary search?

    The list must be sorted (here, in ascending order).

  • What is the time complexity of binary search?

    O(log n), because each comparison halves the part of the list that is left to search. The best case is O(1), when the middle element is the key.

  • At most how many comparisons does binary search need for 1000 elements?

    About 10, because 2¹⁰ = 1024 is more than 1000. Linear search may need up to 1000.

  • Why do some programs write mid = low + (high - low) / 2?

    For very large indexes, low + high can overflow the range of int. low + (high - low) / 2 gives the same middle without that overflow.

  • What is the difference between the recursive and non-recursive versions?

    The non-recursive version uses a while loop and changes low and high. The recursive version calls itself with the new low and high instead of looping.

Learn the concepts

All Programming for Problem Solving Lab experiments →