NBC 103 • Practical #7

Binary Search on a Sorted Array

Aim: To implement Binary Search on an array of N sorted integers with O(log N) complexity.

Step-by-Step Algorithm & Logic

  • 11. Start with sorted array, low = 0, high = size - 1.
  • 22. Loop while (low <= high): mid = low + (high - low) / 2.
  • 33. If (arr[mid] == target), return mid (found).
  • 44. Else if (arr[mid] < target), low = mid + 1 (search right half).
  • 55. Else high = mid - 1 (search left half).
  • 66. If low > high, return -1 (not found).

Complete Tested Source Code

#include <stdio.h>

int binarySearch(int arr[], int size, int target) {
    int low = 0, high = size - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] == target)
            return mid;
        else if (arr[mid] < target)
            low = mid + 1;
        else
            high = mid - 1;
    }
    return -1;
}

int main(void) {
    int arr[] = {11, 23, 34, 45, 56, 67, 78, 89, 99};
    int size = sizeof(arr) / sizeof(arr[0]);
    int target = 67;

    printf("=== Binary Search Algorithm ===\n");
    printf("Sorted Array: ");
    for (int i = 0; i < size; i++) printf("%d ", arr[i]);
    printf("\nTarget to find: %d\n\n", target);

    int index = binarySearch(arr, size, target);
    if (index != -1)
        printf("Success: %d found at Index %d (Position %d)!\n", target, index, index + 1);
    else
        printf("Target %d not present in array.\n", target);

    return 0;
}

Sample Input:

Array = [11, 23, 34, 45, 56, 67, 78, 89, 99], Target = 67

Sample Output:

Success: 67 found at Index 5 (Position 6)!

Practical Exam Viva Questions (Exp #7)

1 Questions
1

What is the precondition for Binary Search?