File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ package search ;
2
+
3
+ import java .util .Scanner ;
4
+
5
+ public class BinarySearch {
6
+ public static void main (String [] args ) {
7
+ Scanner input = new Scanner (System .in );
8
+ System .out .println ("Size of elements" );
9
+ int N = input .nextInt ();
10
+
11
+ int [] inputArr = new int [N ];
12
+
13
+ for (int i = 0 ; i < N ; i ++) {
14
+ System .out .println ("Array[" +i +"] :" );
15
+ inputArr [i ]= input .nextInt ();
16
+ }
17
+
18
+ System .out .println ("Enter the element which you want to search:" );
19
+ int searchElement = input .nextInt ();
20
+ System .out .println ("Output" );
21
+ System .out .println ("index : " + binarySearch (inputArr ,searchElement ));
22
+ }
23
+
24
+ private static int binarySearch (int [] inputArr , int searchElement ) {
25
+
26
+ int first =0 ;
27
+ int last = inputArr .length - 1 ;
28
+
29
+ while (first <=last ){
30
+ int mid = (first + last )/2 ;
31
+ if (searchElement ==inputArr [mid ]){
32
+ return mid ;
33
+ }
34
+ if (searchElement < inputArr [mid ]){
35
+ last = mid -1 ;
36
+ }else {
37
+ first = mid + 1 ;
38
+ }
39
+ }
40
+ return -1 ;
41
+ }
42
+ }
You can’t perform that action at this time.
0 commit comments