Binary search algorithm in java | Searching algorithms

No comments

Binary search is used to find any element in a sorted array.In binary search we start searching for the given element from the mid point of the sorted array.

Steps for binary search in java is given below with example.
Problem -Suppose we have an array of integers, and we want find the index of a particular integer in that array.
Solution-

For binary search in an array of integers, first of all we will have to sort the array in either ascending order or descending order. You can use any sorting algorithm for sorting the array, here we are taking an already sorted array and focusing only on searching instead of sorting.

For solving this problem we wil take a sorted array in ascendig order but you can sort the array in any order as you wish. If you wish to take an array sorted in descending order then you'll have to make the changes suggested below in the code.

For Ascending order - Use the same code described below.
For Descending orde - just swap start = start+1; with end = end-1; in the if conditions given in the code.
Steps -
  • Find length of the given array and initiate the start and end point as 0 and last index of the array respectively.
  • Loop through the array and check if the element at the mid point is equal to the element we are trying to find.
  • If element at mid point is equal to the desired element, return the mid point.
  • If element at mid point is less then the desired element, shift the start point to the right by one position and find the another mid point.
  • If the element at mid point is greater then the desired element, shift the end point to the left by one position and find another mid pont.
  • Start repeating the above 4 steps untill we find the element or start point is less then or equal to the end point.
  • If no match is found, return -1, just to make sure that there is no such element in the array.
The code for binary search in java is given below -
package com.tutorialsinn.binarysearch;

public class BinarySearch {

 public static int searchItem(int a, int arr[]){
  int length = arr.length;
  int start = 0;
  int end = length-1;
  
  while(start<=end){
   int mid = (start+end)/2;
   if(arr[mid] == a){
    return mid;
   }
   if(arr[mid]>a){
    start = start+1;
   }
   if(arr[mid]>a){
    end = end-1;
   }
  }
  
  return -1;
 }
 
 public static void main(String[] args) {
  int [] arr = {1,12,20,34,44,45,76,98,104,300};
  
  System.out.println(searchItem(44, arr) == -1 ? "No such element found" : "element is found at index "+searchItem(44, arr));
 }

}
In above code we are tryin to find the index of integer 44, so the output will be -
Output - element is found at index 4
If you have any confusion in the solution provided above or have some queries, please feel free to leave your answer in the comment box below.

No comments :

Post a Comment