2
2
* Part of Cosmos by OpenGenus Foundation
3
3
*/
4
4
class Search
5
- {
5
+ {//Implementation of Binary Search in java
6
6
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
8
8
if (r >=l )
9
9
{
10
- int mid = l + (r - l )/2 ;
10
+ int mid = l + (r - l )/2 ; //finding out the middle index
11
11
12
12
if (arr [mid ] == x )
13
- return mid ;
13
+ return mid ; //If x is present at the middle
14
14
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.
16
16
return recursiveBinarySearch (arr , l , mid -1 , x );
17
17
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
19
19
}
20
- return -1 ;
20
+ return -1 ; //-1 is returned if the element x is not present in the array
21
21
}
22
22
23
23
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)
26
26
{
27
- int mid = l + (r -l )/2 ;
27
+ int mid = l + (r -l )/2 ; //Calculating middle index
28
28
29
29
if (arr [mid ] == x )
30
- return mid ;
30
+ return mid ; //if the element x is present on middle index
31
31
32
- if (arr [mid ] < x )
32
+ if (arr [mid ] < x ) //If x greater, ignore left half
33
33
l = mid + 1 ;
34
34
35
35
else
36
- r = mid - 1 ;
36
+ r = mid - 1 ; // If x is smaller, ignore right half
37
37
}
38
- return -1 ;
38
+ return -1 ; //if the element is not present in the array,-1 is returned
39
39
}
40
40
41
41
public static void main (String args [])
42
42
{
43
43
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
46
46
System .out .println ("Position of " +find +" is " +recursiveBinarySearch (arr ,0 ,size -1 ,find ));
47
47
System .out .println ("Position of " +find +" is " +binarySearch (arr ,0 ,size -1 ,find ));
48
48
}
49
- }
49
+ }
0 commit comments