Skip to content

Commit fed98d7

Browse files
committed
Binary Search
1 parent 2ad535d commit fed98d7

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Array_1D/BinarySearch.java

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*Code Binary Search
2+
You have been given a sorted(in ascending order) integer array/list(ARR) of size N and an element X. Write a function to search this element in the given input array/list using 'Binary Search'. Return the index of the element in the input array/list. In case the element is not present in the array/list, then return -1.*/
3+
4+
package PracticeMore;
5+
6+
import java.util.Scanner;
7+
8+
public class BinarySearch
9+
{
10+
public static int binarySearch(int[]arr, int x)
11+
{
12+
int min = 0;
13+
int max = arr.length-1;
14+
15+
for(int i=0;i<arr.length;i++)
16+
{
17+
int mid = (min+max)/2;
18+
if(arr[mid]<x)
19+
{
20+
min= mid+1;
21+
}
22+
else if(arr[mid]>x)
23+
{
24+
max= mid-1;
25+
}
26+
else
27+
{
28+
return mid;
29+
}
30+
}
31+
32+
return -1;
33+
}
34+
35+
public static void printArray(int arr[])
36+
{
37+
for(int i= 0; i<arr.length; i++)
38+
{
39+
System.out.print(arr[i]+ ", ");
40+
}
41+
System.out.println();
42+
}
43+
44+
public static void main(String[] args)
45+
{
46+
Scanner sc = new Scanner(System.in);
47+
System.out.print("Enter the size of array : ");
48+
int size = sc.nextInt();
49+
System.out.print("Enter the number for search : ");
50+
int number = sc.nextInt();
51+
int[] input_arr = new int[size];
52+
53+
for(int i=0; i<size; i++)
54+
{
55+
System.out.print("Enter the element at "+ i + "th term : ");
56+
input_arr[i] = sc.nextInt();
57+
}
58+
59+
printArray(input_arr);
60+
61+
int index = binarySearch(input_arr, number);
62+
System.out.print("Index of given number in array : "+index);
63+
}
64+
}

0 commit comments

Comments
 (0)