Skip to content

Commit 3849c2c

Browse files
authored
Added Comments
1 parent 0eba1e7 commit 3849c2c

File tree

1 file changed

+17
-17
lines changed

1 file changed

+17
-17
lines changed

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

+17-17
Original file line numberDiff line numberDiff line change
@@ -2,48 +2,48 @@
22
* Part of Cosmos by OpenGenus Foundation
33
*/
44
class Search
5-
{
5+
{//Implementation of Binary Search in java
66
static int recursiveBinarySearch(int arr[], int l, int r, int x)
7-
{
7+
{//recursive function that returns the index of element x if it is present in arr[],else returns -1
88
if (r>=l)
99
{
10-
int mid = l + (r - l)/2;
10+
int mid = l + (r - l)/2; //finding out the middle index
1111

1212
if (arr[mid] == x)
13-
return mid;
13+
return mid; //If x is present at the middle
1414

15-
if (arr[mid] > x)
15+
if (arr[mid] > x) //If x is smaller than the element at middle,then it might be present in the left of middle.
1616
return recursiveBinarySearch(arr, l, mid-1, x);
1717

18-
return recursiveBinarySearch(arr, mid+1, r, x);
18+
return recursiveBinarySearch(arr, mid+1, r, x); //else the element can only be present in the right subarray
1919
}
20-
return -1;
20+
return -1; //-1 is returned if the element x is not present in the array
2121
}
2222

2323
static int binarySearch(int arr[], int l, int r, int x)
24-
{
25-
while (l <= r)
24+
{//Iterative implementation of Binary Search
25+
while (l <= r) //the loop runs till the low index(l) is less than or equal to the high index(r)
2626
{
27-
int mid = l + (r-l)/2;
27+
int mid = l + (r-l)/2; //Calculating middle index
2828

2929
if (arr[mid] == x)
30-
return mid;
30+
return mid; //if the element x is present on middle index
3131

32-
if (arr[mid] < x)
32+
if (arr[mid] < x) //If x greater, ignore left half
3333
l = mid + 1;
3434

3535
else
36-
r = mid - 1;
36+
r = mid - 1; // If x is smaller, ignore right half
3737
}
38-
return -1;
38+
return -1; //if the element is not present in the array,-1 is returned
3939
}
4040

4141
public static void main(String args[])
4242
{
4343
int arr[] = {1, 2, 3, 5};
44-
int size = arr.length;
45-
int find = 3;
44+
int size = arr.length; //stores the length of arr[]
45+
int find = 3; //Element to be searched
4646
System.out.println("Position of "+find+" is "+recursiveBinarySearch(arr,0,size-1,find));
4747
System.out.println("Position of "+find+" is "+binarySearch(arr,0,size-1,find));
4848
}
49-
}
49+
}

0 commit comments

Comments
 (0)