Basic Overview:
A binary search algorithm finds the position of a specified input value within an array sorted by key value.
For binary search, the array should be sorted i.e. arranged in ascending or descending order.
In Binary search, the search key value with the key value of the middle element of the array. If the key element match, then a matching element has been found and its position, is returned.
If the search key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right.
If the remaining array to be searched is empty, then the key cannot be found in the array and a “key is not found” message returned.
Steps are as follows:
Create new java class
Write the code for binary search algorithm as follows:
package com.javabykiran.binarysearch;
import java.util.Scanner;
public class JbkBinarySearch {
public static int binarySearch(int arr[], int first, int last, int key) {
if (last >= first) {
int mid = first + (last - first) / 2;
if (arr[mid] == key) {
return mid;
}
if (arr[mid] > key) {
return binarySearch(arr, first, mid - 1, key); // search in left subarray
} else {
return binarySearch(arr, mid + 1, last, key); // search in right subarray
}
}
return -1;
}
public static void main(String args[]) {
int arr[];
int counter = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter total number of elements :");
int numberOfElements = input.nextInt();
// Creating array to store the numbers of size n
arr = new int[numberOfElements];
System.out.println("Enter " + numberOfElements + " integers in ascending order");
// Loop to store each entered number in array
for (counter = 0; counter < numberOfElements; counter++)
arr[counter] = input.nextInt();
System.out.println("Enter a key to be seached");
int key = input.nextInt();
int last = arr.length - 1;
int result = binarySearch(arr, 0, last, key);
if (result == -1)
System.out.println("Element is not found!");
else
System.out.println("Element is found at index: " + result);
}
}
Now run the programs as Java Application
Enter the total number of elements on console.
Enter the elements one by one in ascending order.
Enter the number to be searched and the key will be searched.
Press Enter to check whether element is present or not in array.
Output Window: