Binary Search:
- Another searching algorithm to search an element in the array.
- In binary search, we find the mid element of array and compare with the element to be searched. If element matches, we return mid location as element location.
- If the element is less than mid location element, search continues in the left side array of mid location.
- If the element is greater than mid location element, search continues in right side array.
- This process continues with iterator until element found.
import java.util.Scanner ; class Demo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print(“Enter array size : “); int n = scan.nextInt(); int arr[ ] = new int[n]; System.out.println(“Enter ” + n + ” values : “); for (int i=0 ; i<n ; i++){ arr[i] = scan.nextInt(); } System.out.println(“Enter element to search : “); int ele = scan.nextInt(); boolean found=false; int low=0; int high=n-1; while(low <= high){ int mid = (low+high)/2; if(ele < arr[mid]){ high = mid-1; } else if(ele > arr[mid]){ low = mid+1; } else if(ele == arr[mid]){ System.out.println(“Element found at location : ” + mid); found = true; break; } } if(!found) System.out.println(“Element not found”); } } |