Binary search algorithm

Category : Data-structures-algorithms | Sub Category : Search Algorithms | By Prasad Bonam Last updated: 2020-11-01 08:50:16 Viewed : 479


Binary search algorithm


Example: BinarySearch.java

 

 import java.util.Scanner; 

public class BinarySearch {

     int binarySearch(int array[], int element, int low, int high) { 

           // Repeat until the pointers low and high meet each other

           while (low <= high) { 

                // get index of mid element

                int mid = low + (high - low) / 2; 

                // if element to be searched is the mid element

                if (array[mid] == element)

                      return mid;

 

                 // search only the left side of mid

                if (array[mid] < element)

                      low = mid + 1;

 

                // if element is greater than mid element

                // search only the right side of mid

                else

                      high = mid - 1;

           }

 

           return -1;

     }

 

     public static void main(String args[]) {

 

           // create an object of Main class

           BinarySearch obj = new BinarySearch();

 

           // create a sorted array

           int[] array = { 13, 14, 15, 16, 17, 18, 19 };

           int n = array.length;

 

           // get input from user for element to be searched

           Scanner input = new Scanner(System.in);

 

           System.out.println("Enter element to be searched:");

 

           // element to be searched

           int element = input.nextInt();

           input.close();

 

          int result = obj.binarySearch(array, element, 0, n - 1);

           if (result == -1)

                System.out.println("Element is not ");

           else

                System.out.println("Element found at index: " + result);

     }

}

                                                  

 Ouput:

       Enter element to be searched:

        17

    Element found at index: 4

Search
Related Articles

Leave a Comment: