×

Binary Search in C with Best and Worst Time Complexity

What is Binary Search?

Binary search is an algorithm that is used to find an element in a sorted array efficiently. It has a time complexity of O(log n). It means that the time taken by the algorithm grows logarithmically with the size of the input respectively.

Here is an example of how to implement binary search in C.

Example 1:

#include <stdio.h>
int binary_search(int arr[], int n, int x)
{
int low = 0;
int high = n - 1;


while (low <= high)
    {
int mid = (low + high) / 2;


if (arr[mid] == x)
return mid;
else if (arr[mid] < x)
low = mid + 1;
else
high = mid - 1;
    }


return -1;
}


int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 3;


int result = binary_search(arr, n, x);


if (result == -1)
printf("Element not found in array\n");
else
printf("Element found at index %d\n", result);


return 0;
}

Output:

Element found at index 2

Here is another example to explain the same.

Example 2:

#include <stdio.h>
int binarySearch(int array[], int size, int value) {
int low = 0;
int high = size - 1;
int mid;


while (low <= high) {
mid = (low + high) / 2;


if (array[mid] == value) {
return mid;
        } else if (array[mid] < value) {
low = mid + 1;
        } else {
high = mid - 1;
        }
    }


return -1;
}


int main() {
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int size = sizeof(array) / sizeof(array[0]);
int value = 5;
int index = binarySearch(array, size, value);


if (index == -1) {
printf("Value not found\n");
    } else {
printf("Value found at index %d\n", index);
    }


return 0;
}

Output:

Value found at index 4

This implementation takes an array of integers, the size of the array, and the value to search for as input. It returns the index of the value in the array if it is found, or “Element not found in array” if it is not found.

The function uses a binary search algorithm to search for the value in the array. It works by dividing the array into halves and comparing the value at the midpoint of the array with the target value. If the value is equal to the target value, it returns the index. If the value is less than the target value, it searches the right half of the array. If the value is greater than the target value, it searches the left half of the array. This process is repeated until the value is found or it is clear that the value is not present in the array.

Time Complexity of Binary Search in C

The time complexity of binary search in C (or any other language) is O(log n), where n is the size of the input array.

This means that the time taken by the algorithm grows at a logarithmic rate as the size of the input array increases. This makes binary search very efficient for large arrays, as the time taken to search the array increases slowly as the array grows.

For example, if the array has a size of 1,000, it will take at most 10 comparisons to find the value (since log2(1000) is approximately 10). If the array has a size of 1,000,000, it will take at most 20 comparisons to find the value (since log2(1,000,000) is approximately 20).

In contrast, a linear search algorithm, which searches for a value by examining each element of the array one by one, has a time complexity of O(n), meaning that the time taken by the algorithm grows linearly with the size of the input array. This makes linear search less efficient for large arrays.

Best case:

When the element that is being searched for is the first element in the array then the best case time complexity of binary search is O(1).However, in the best case, the time complexity of binary search is O(1). This happens when the element being searched for is the middle element in the array. In this case, the algorithm finds the element in just only one step.

Worst Case:

The worst case time complexity is O(log n) when the element being searched for is not present in the array or is present at the end of the array. This occurs when the element being searched for is not present in the array and the algorithm has to search the entire array.

Overall, binary search is a very efficient algorithm for searching a sorted array and is much faster than linear search, which has a time complexity of O(n).


Related Topics

C Program for Mean and Median of an Unsorted Array

In this tutorial, we will look at how to determine the mean and median of a given unsorted array. To determine the Mean: To get the average, mean is determined. The formula...

2 minutes read.

Static function in C

The functions in the C programming language are by default global. This means the programmer can easily access the function which is outside from the file where it was initially...

3 minutes read.

tolower() Function in C

The tolower() capability is characterized in the ctype.h header document. In the event that the person passed is a capitalized letter set, the tolower() capability switches capitalized letters in order...

3 minutes read.

Array Of Structures in C

The C programming language allows us to store multiple elements of the same type in arrays. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

Passing Array to Function in C

Need to pass Arrays? The need to pass arrays to a function arises when we need to pass a list of values to a given function. During the course of our programming...

4 minutes read.

C Program to find the Roots of a Quadratic Equation

What is Quadratic Equation: Equations of degree 2 in polynomial form are called quadratic equations. A, B, and C are the coefficient variables in the equation, which is written as ax2...

3 minutes read.

Garbage in C

Garbage in C The C programming language is a perfect fit for embedded systems as it provides low level control, structured programming, and portability. On the contrary, it does not provide...

3 minutes read.

How to get ASCII value in C

For text data on computers and the internet, ASCII (American Standard Code for Information Interchange). It is the most widely used character encoding standard. One hundred twenty-eight alphabetic, numeric, special...

3 minutes read.

Typedef vs define in C

Typedef VS define in C Typedef In the C programming language, a keyword called typedef can be used to give a type a new name. In other words, it is used to...

5 minutes read.

Tower of Hanoi in C

What is Tower of Hanoi? The Tower of Hanoi is a gaming problem that was created in 1883 by a French mathematician named Édouard Lucas. The Tower of Hanoi temple in...

4 minutes read.

Built-in functions in C

The function is a set of instructions and statements enclosed in the "{}" delimiter. In c, there are two types of functions. Pre-define functions/ Built-in functionsUser define function. Built-in functions in C:- These...

8 minutes read.

How to convert a string to hexadecimal in C

Converting a character array or any string to its respective hexadecimal form is simple. The only thing we have to do is to follow the below steps. Take each character from...

3 minutes read.

Recursion in C

Recursion in C: In the C programming language, the concept known as recursion exists that is a technique in which a function calls itself either directly or indirectly. It allows...

4 minutes read.

How to use Typedef Struct in C

The “typedef” is a predefined keyword in C programming language which is used to declare the new name to an existing type of variable. For better understanding, if you declare a...

3 minutes read.

Ceil and Floor in C

In arithmetic, a rational number is a number that can be expressed as the quotient p/q of two integers. Where q is zero. The set of rational numbers includes all...

6 minutes read.

C program to compare the two strings

C program to compare the two strings Strings can be compared either by using the string function or without using string function. First, we will look at how we can compare the strings with...

4 minutes read.

Local Labels in C

Anyone who has written programs in the C programming language is required to be familiar with the "go to" and "labels" used in C to navigate between functions. "Local labels"...

4 minutes read.

C –Structure

C structure is a collection of different types of data that is grouped together. It is used to represent records.Structkeyword is used to create a structure. Each element of a...

1 minute read.

Find the Largest Three Distinct Elements in an Array using C/C++

In this tutorial, we will demonstrate how to use a C/C++ programme to locate the highest three different elements in an array. C/C++ Program to Find the Largest Three Different Elements...

3 minutes read.

How to Merge Array in C?

Introduction Merging arrays is a common task for many developers but might be difficult for beginners of C programming. Fortunately, our guide will show you how to quickly merge arrays in...

6 minutes read.