Skip to content

Commit fbaefc6

Browse files
authored
Merge pull request #4465 from AJAYSHARMA2012/master
Added comments in binary.c file
2 parents a169a64 + e426689 commit fbaefc6

File tree

1 file changed

+26
-8
lines changed

1 file changed

+26
-8
lines changed

Diff for: code/search/src/binary_search/binary_search.c

+26-8
Original file line numberDiff line numberDiff line change
@@ -2,46 +2,64 @@
22
/*
33
* Part of Cosmos by OpenGenus Foundation
44
*/
5+
// A recursive binary search function. It returns
6+
// location of x in given array arr[l..r] is present,
7+
// otherwise -1
58
int recursiveBinarySearch(int arr[], int l, int r, int x)
69
{
710
if (r >= l)
811
{
912
int mid = l + (r - l)/2;
10-
13+
// If the element is present at the middle
14+
// itself
1115
if (arr[mid] == x)
1216
return mid;
17+
// If element is smaller than mid, then
18+
// it can only be present in left subarray
1319
if (arr[mid] > x)
1420
return recursiveBinarySearch(arr, l, mid-1, x);
15-
21+
// Else the element can only be present
22+
// in right subarray
1623
return recursiveBinarySearch(arr, mid+1, r, x);
1724
}
25+
// We reach here when element is not
26+
// present in array
1827
return -1;
1928
}
20-
29+
// A iterative binary search function. It returns
30+
// location of x in given array arr[l..r] is present,
31+
// otherwise -1
2132
int binarySearch(int arr[], int l, int r, int x)
2233
{
2334
while (l <= r)
2435
{
2536
int mid = l + (r-l)/2;
26-
37+
// If the element is present at the middle
38+
// itself
2739
if (arr[mid] == x)
2840
return mid;
29-
41+
// If element is greater than mid, then
42+
// it can only be present in right subarray
3043
if (arr[mid] < x)
3144
l = mid + 1;
32-
45+
// Else the element can only be present
46+
// in right subarray
3347
else
3448
r = mid - 1;
3549
}
36-
return -1;
50+
// We reach here when element is not
51+
// present in array
52+
return -1;
3753
}
3854

3955
int main(void)
4056
{
4157
int arr[] = {1, 2, 3, 5};
4258
int size = sizeof(arr)/ sizeof(arr[0]);
4359
int find = 3;
60+
//Printing the position of element using recursive binary search
4461
printf("Position of %d is %d\n", find, recursiveBinarySearch(arr, 0, size-1, find));
62+
//Printing the position of element using iterative binary search
4563
printf("Position of %d is %d\n", find, binarySearch(arr, 0, size-1, find));
4664
return 0;
47-
}
65+
}

0 commit comments

Comments
 (0)