For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
Binary search is a robust algorithm with various applications aiming to serve its purpose across aspects of computer science, numerical solutions, data processing, and many more. In C programming, binary search can be implemented using iterative or recursive approaches. The algorithm's efficiency and simplicity make it a fundamental tool for searching and other related operations in various applications.
The most widely used algorithm in the C programming language, Binary Search, primarily takes a divide-and-conquer approach to determine the target value within a sorted array.
Here is a detailed guide to facilitate your understanding of how binary search in C exactly operates.
We have to continue computing the middle index and adjust the search space until it becomes empty, that is, start > end. When this happens, and the target value is not found, it denotes that the target value does not exist in the array. At this point, we can either return a special value or perform any desired action to highlight that the target value was not found.
Binary search is not only limited to finding a specific target value in a sorted array but can be applied in various other scenarios. Here are some common use cases for binary search:
There are two main approaches for implementing the binary search algorithm. These approaches are:
Iterative binary search, as the name suggests, is when the algorithm uses a loop-based approach to efficiently search for a target value with a sorted array.
The basic structure of iterative binary search in C goes as follows,
#include <stdio.h>
int binarySearch(int array[], int size, int target) {
int startIndex = 0;
int endIndex = size - 1;
while (startIndex <= endIndex) {
int midIndex = startIndex + (endIndex - startIndex) / 2;
if (array[midIndex] == target) {
return midIndex; // Target value found at index mid
} else if (array[midIndex] < target) {
startIndex = midIndex + 1; // Target value is in the upper half
} else {
endIndex = midIndex - 1; // Target value is in the lower half
}
}
return -1; // Target value not found in the array
}
int main() {
// Example usage
int array[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int size = sizeof(array) / sizeof(array[0]);
int target = 23;
int result = binarySearch(array, size, target);
if (result != -1) {
printf("Target value found at index %d\n", result);
} else {
printf("Target value not found in the array\n");
}
return 0;
}
Contrary to the former, recursive binary search is used when the algorithm adapts to a recursive approach to locate the target value with a sorted array. This means that instead of using the loop, the array is divided in half and recursively calls itself on the appropriate subarray. This continues till the target value is found or the search space is exhausted.
Let’s take a look at a small example of using recursive binary search in C,
#include <stdio.h>
int binarySearch(int array[], int startIndex, int endIndex, int target) {
if (startIndex <= endIndex) {
int midIndex = startIndex+ (endIndex - startIndex) / 2;
if (array[midIndex] == target) {
return midIndex; // Target value found at index mid
} else if (array[midIndex] < target) {
return binarySearch(array, midIndex + 1, endIndex, target); // Recursively search in the upper half
} else {
return binarySearch(array, startIndex, midIndex - 1, target); // Recursively search in the lower half
}
}
return -1; // Target value not found in the array
}
int main() {
// Example usage
int array[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int size = sizeof(array) / sizeof(array[0]);
int target = 23;
int result = binarySearch(array, 0, size - 1, target);
if (result != -1) {
printf("Target value found at index %d\n", result);
} else {
printf("Target value not found in the array\n");
}
return 0;
}
To apply binary search in a data structure, it needs to meet two specific conditions. They are, namely,
Sorted Data
The data structure must be sorted either in ascending order or descending for the binary search. Furthermore, the elements must also be arranged accordingly so that it can allow identification and comparison of the target value.
Random Access
Secondly, binary search bears fruitful results when random access to elements is allowed. Thus, you can access the elements quite easily through their indices.
Once both these conditions have been satisfied, you can apply binary search on multiple data structures, including arrays, and balanced binary search trees, among others. Please note that binary search is not at all advisable for unsorted arrays since it can generate unwanted results. In such cases, using other tools, such as hashing or linear search, is best.
Various search algorithms are used in computer science to look for an element in a list. To understand and compare the efficiency of each of those algorithms, we primarily use space and time complexities.
Space and time complexities of binary search algorithms enable it to quickly retrieve elements and outperform other tools, such as linear search, especially when dealing with large data sets.
Time Complexity
The time complexity is logarithmic. This means that the search space is broken in half with each comparison. One of the major benefits of this approach is that the number of comparisons usually required for finding the target element remains small, even in large input sizes.
Space Complexity
Space complexity denotes the memory usage for programs that have large inputs. It is usually constant, meaning that the additional amount of memory used will always remain constant irrespective of the input size.
The middle index in binary search is calculated by generating an average of the lower index ‘low’ and higher index ‘high. The syntax for the same goes as follows,
mid = low + (high - low) / 2;
This is especially useful when you are handling large indices and prevents the occurrence of integer overflow. However, that being said, please note that simply using (low + high) / 2 might not always generate the desired result. This is because it can often cause an integer overflow when the higher and lower index sum exceeds the maximum value that an integer data type can represent. Therefore, using (high - low) / 2 is always advisable to avoid such issues.
Binary search has been deemed an essential tool in various applications, especially where efficient searching is required. It offers many benefits to the users. A few of the same have been highlighted below.
While citing the advantages of binary search in C, you must also consider the downsides of it as well.
To sum up, binary search is undoubtedly quite an important tool with numerous applications. From data processing to solving range query problems, the list continues. It also brings many advantages to the table, implying its significance. That being said, knowing when to use and how to use binary search is also crucial. Furthermore, some conditions must be fulfilled for binary search to operate properly.
To know more about the same, do not forget to check out upGrad’s MS in Computer Science Program offered under the leading Liverpool John Moores University. The program is specifically curated for aspirants wishing to boost their knowledge and career in programming languages.
So what are you waiting for? Enroll now!
Q1: What are the two types of binary search?
Binary search implementation can primarily be done in two ways. They are, namely, recursive binary search and iterative binary search. The former has a space complexity of O(log N), while the latter uses O(1).
Q2: Why is binary search considered to be the best?
Compared to other algorithms, such as Linear search, binary search is much faster to execute and implement. Furthermore, it uses the divide and conquer approach, wherein only half of the list is searched instead of going through every element. For all these reasons, binary search is considered to be the most efficient.
Q3: Can you name some search algorithms?
Linear search, binary search, jump search, exponential search, and Fibonacci search are examples of some of the many search algorithms used by programmers.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.