Binary Search in Java
Binary search is a more efficient searching algorithm, in comparison to linear search. It repeatedly divides the search range in half until it finds the target element. Below is how you can perform a Binary Search in Java program:
Binary Search in Java program
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 40 | import java.util.Scanner; public class BinarySearch{ public static int binarySearch(int[] arr, int tg) { int left = 0; int right = arr.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == tg) { return mid; } if (arr[mid] < tg) { left = mid + 1; } else { right = mid - 1; } } return -1; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of elements : "); int n = scanner.nextInt(); int[] numbers = new int[n]; System.out.println("Input "+ n +" numbers :"); for (int i = 0; i < n; i++) { numbers[i] = scanner.nextInt(); } System.out.print("Input the number to search : "); int tg = scanner.nextInt(); scanner.close(); int index = binarySearch(numbers, tg); if (index != -1) { System.out.println("Element " + tg + " exist at index " + index); } else { System.out.println("Element " + tg + " not exist in the array."); } } } |
Output
C:\CodeRevise\java>javac BinarySearch.java
C:\CodeRevise\java>java BinarySearch
Enter the number of elements : 5
Input 5 numbers :
10
20
35
45
68
Input the number to search : 45
Element 45 exist at index 3
Check out our other Java Programming Examples