×

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

Nested loop in C

Definition of Nested Loop A nested loop is generally used when we want to run a loop statement inside another loop statement. This kind of loop is also known as a...

3 minutes read.

Kruskal algorithm in C

Given a weighted graph, Kruskal's algorithm generates a spanning tree with the lowest possible weights. Start by creating an edge list for the given graph, including the weights. Sort the...

3 minutes read.

Positioning of file in C

Positioning() function in c The fseek() function is utilized to change the document position of the stream . The fully extent of value from the source should be one of the...

3 minutes read.

Binomial Coefficient Program in C

What is Binomial coefficient? In the given set of n possibilities, the binomial coefficient(n,k) indicates the order of choosing 'K' results from those possibilities. Binomial coeeficient of posistive n and k...

3 minutes read.

Find reverse of an array in C using functions

Introduction: Here, we describe how to find the reverse array in C using functions. Suppose you have an array with n elements. I need to display the elements present in...

3 minutes read.

Displaying Array in C

Reference a collection of variables of similar data type in an array using a single element. The parts are stored next to each other. When declaring an array, you must specify...

4 minutes read.

Armstrong program in C using function

In this article we will learn how to find Armstrong of a number using function in C. An Armstrong number is a three-digit number that is the sum of its separate...

1 minute read.

Caesar Cipher Program in C

What is Caesar Cipher? The Caesar Cipher is a type of substitution cipher that is named after Julius Caesar, who is said to have used it to encrypt messages sent to...

2 minutes read.

pow() function in C

pow() function is one of the in-built functions present in math.h header file Power function is used to calculate the powers of the given number. The syntax of the power...

3 minutes read.

How to measure time taken by a function in C?

Measuring the time taken by a function is quite a complex task, because numerous methods are frequently not transferable to other platforms, measuring the execution time of a C programs...

5 minutes read.

How to use atoi() function in C

Introduction: The atoi() is a function used in C programming language. This function converts string characters to the integer value. The atoi() function converts the input string to the return type of...

4 minutes read.

How to create a node in C?

A node is a small concept taken from the graph theory, or a node is a fundamental unit of a data structure, like a tree data structure. Every graph contains...

3 minutes read.

Character Set in C

Introduction Every language has some basic elements which are used to represent information. The English language includes alphabets which together shape a sentence, after which the sentences are used to shape...

3 minutes read.

Use of Structure in C

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

4 minutes read.

Assert() Function in C

Assert (): In C, the statements are executed with the exit statement. In C language declare, and it tests the condition parameters. If the statement executed will be false, it shows...

4 minutes read.

Header files in C

Header files in C In the C programming language, header files are present, which have an extension of ‘.h’, and it consists of macro definitions, declarations, and so on that are...

4 minutes read.

Floyd’s triangle in C

Floyd’s triangle in C Floyd’s triangle is named after a person Robert Floyd. It is a right-angled triangle that is of natural numbers starting from 1 and consecutively selects the upcoming...

4 minutes read.

SJF Scheduling Program in C

The SJF (shortest job first) or the shortest job next is the programming scheduling in the C. It is one of the CPU scheduling programming. The SJF is defined as...

4 minutes read.

Matrix Multiplication in C

Matrix Multiplication in C Matrix multiplication in C: Two matrices can be added, subtracted, multiplied, and divided. To do so, we take input from the consumer for row number, column number, first element matrix,...

3 minutes read.

Armstrong Number in C

The Armstrong number is defined as the sum of each of its digits to the power of the number base for the each given number with any given number base....

3 minutes read.