-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.java
More file actions
39 lines (27 loc) · 806 Bytes
/
binarysearch.java
File metadata and controls
39 lines (27 loc) · 806 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class binarysearch{
// function defined
public static int binarysearch(int arr[],int element, int left, int right){
if(left <= right){
int mid = (left + right)/2;
if(arr[mid] == element)
return mid;
else if (arr[mid] > element)
return binarysearch( arr, element , left , mid-1);
else
return binarysearch( arr, element , mid+1 , right);
}
return -1;
}
// main function
public static void main(String args[]){
//define array
int num[] = {4,7,2,8,1,11,3};
// function call
int n = 11;
int index = binarysearch(num ,n, 0,num.length );
if(index == -1)
System.out.println( "The element is not present in the list.");
else
System.out.println( "The index of "+n +" is "+ index+"." );
}
}