Skip to content

Commit 804396f

Browse files
author
Pragati Gupta
committed
Add: Binary Search in C
- Implements efficient search in a sorted array using iterative binary search - Time Complexity: O(log n) - Space Complexity: O(1)
1 parent e3274eb commit 804396f

1 file changed

Lines changed: 37 additions & 20 deletions

File tree

CPP/algorithms/searching/binary_search.cpp

Lines changed: 37 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,46 @@
1-
#include <iostream>
2-
using namespace std;
3-
4-
// Function to perform Binary Search
1+
#include <stdio.h>
2+
3+
/*
4+
=========================================================
5+
Algorithm Name: Binary Search
6+
Category: Searching
7+
Difficulty Level: Easy (Beginner friendly)
8+
9+
Algorithm Description:
10+
Binary search is an efficient algorithm used to find the position
11+
of a target value within a sorted array. It works by repeatedly
12+
dividing the search interval in half. If the value of the search key
13+
is less than the item in the middle of the interval, the algorithm
14+
continues on the left half, otherwise on the right half.
15+
16+
Time Complexity:
17+
- Best Case: O(1) (target is at the middle)
18+
- Average Case: O(log n)
19+
- Worst Case: O(log n)
20+
21+
Space Complexity:
22+
- O(1) (iterative implementation uses constant extra space)
23+
=========================================================
24+
*/
25+
26+
// Function to perform Binary Search on a sorted array
527
int binarySearch(int arr[], int size, int target) {
6-
int left = 0, right = size - 1;
28+
int left = 0; // Start of the search interval
29+
int right = size - 1; // End of the search interval
730

831
while (left <= right) {
9-
int mid = left + (right - left) / 2; // Calculate mid index
32+
int mid = left + (right - left) / 2; // Middle index
1033

11-
// Check if the target is at mid
1234
if (arr[mid] == target) {
13-
return mid; // Return the index if found
14-
}
15-
16-
// If target is greater, ignore the left half
17-
if (arr[mid] < target) {
18-
left = mid + 1;
19-
}
20-
// If target is smaller, ignore the right half
21-
else {
22-
right = mid - 1;
35+
return mid; // Target found, return its index
36+
} else if (arr[mid] < target) {
37+
left = mid + 1; // Ignore left half
38+
} else {
39+
right = mid - 1; // Ignore right half
2340
}
2441
}
2542

26-
return -1; // Return -1 if the target is not found
43+
return -1; // Target not found
2744
}
2845

2946
int main() {
@@ -36,9 +53,9 @@ int main() {
3653

3754
// Output the result
3855
if (result != -1) {
39-
cout << "Element found at index: " << result << endl;
56+
printf("Element found at index: %d\n", result);
4057
} else {
41-
cout << "Element not found!" << endl;
58+
printf("Element not found!\n");
4259
}
4360

4461
return 0;

0 commit comments

Comments
 (0)