Binary Search in C Language

Source Code

#include <stdio.h>

void binarySearch(int arr[], int left, int right, int key) {
	while(left <= right) {
		int mid = left + (right-1) / 2;
		if(arr[mid] == key) { printf("Element is present in the array\n"); return; }
		if(key > arr[mid]) left=mid+1;
		else right=mid-1;
	}
	printf("Element is not present in the array!\n");
	return;
}

int main()
{
    int n = 9;
    int arr[] = {10, 8, 1, 21, 7, 32, 5, 11, 0};
    int key = 56;

    // function call
    binarySearch(arr, 0, n-1, key);

    return 0;
}

Time Complexity

O(log(n)) where 'n' is the size of the array

Other videos in this series

Back To Home