File tree Expand file tree Collapse file tree 4 files changed +39
-0
lines changed Expand file tree Collapse file tree 4 files changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ Binary search
2
+
3
+ Question- Given a sorted array of numbers and a number, find if the given number exists in the array in O(nlogn) time and O(1) space.
Original file line number Diff line number Diff line change
1
+ #BlueJ class context
2
+ comment0.target=bs
3
+ comment1.params=arr\ n
4
+ comment1.target=boolean\ binary_search(int[],\ int)
5
+ comment2.params=args
6
+ comment2.target=void\ main(java.lang.String[])
7
+ numComments=3
Original file line number Diff line number Diff line change
1
+ class bs
2
+ {
3
+ public boolean binary_search (int arr [], int n )
4
+ {
5
+ int right ;int left ; int mid ;
6
+ right = arr .length ;
7
+ left =0 ;
8
+ do {
9
+ mid = (right +left )/2 ;
10
+ if (arr [mid ]==n )
11
+ return true ;
12
+ if (arr [mid ]>n )
13
+ right = mid -1 ;
14
+ else
15
+ left = mid +1 ;
16
+ }while ((arr [mid ]!=n )&&(left !=right ));
17
+ return false ;
18
+ }
19
+ public static void main (String args [])
20
+ {
21
+ bs obj = new bs ();
22
+ int a []={1 ,2 ,3 ,4 ,5 };
23
+ int n = 5 ;
24
+ if (obj .binary_search (a ,n ))
25
+ System .out .println ("Element found" );
26
+ else
27
+ System .out .println ("Element is not present" );
28
+ }
29
+ }
You can’t perform that action at this time.
0 commit comments