Binary Search
Efficient O(log n) search on a sorted array.
package DSA.Arrays;
import java.util.*;
public class binarySearch { public static int binary(int arr[], int key) { int start = 0, end = arr.length - 1; while (start <= end) { int mid = (start + end) / 2; if (arr[mid] == key) { return mid; } else if (arr[mid] < key) { start = mid + 1; } else if (arr[mid] > key) { end = mid - 1; } } return -1; }
public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { System.out.println("Enter the length of the array: "); int length = sc.nextInt(); System.out.println("Enter the arr elements in sorted order"); int numbers[] = new int[length]; for (int i = 0; i < numbers.length; i++) { numbers[i] = sc.nextInt(); }
System.out.println("Enter the element to Search: "); int key = sc.nextInt(); int result = binary(numbers, key); System.out.println("Element is present at index:" + result); } catch (Exception e) { System.out.println(e); } }}