Friday, January 3, 2020

Binary Search Example

Binary Search is first searching algorithm.  The binary search algorithm works on sorted arrays that means if we have non-sorted array we must sort array then implement Binary Search.
It will start search with mid index and continues searching in repeated manner.

package ds.search.algorithms;

public class BinarySearchExample {

 public static void main(String[] args) {

  int arr[] = { 13, 21, 54, 81, 90 };
  int n = arr.length;
  int search = 81;

  int result = binarySearch(arr, n, search);

  if (result == -1) {
   System.out.println("Element is not present in the given array.");
  } else {
   System.out.println("Element is present at index: " + result);
  }
 }

 public static int binarySearch(int values[], int arrLen, int search) {

  int max = (arrLen - 1);
  int min = 0;
  int mid; // this will hold the index of middle elements
  int step = 0; // to find out in how many steps we completed the search

  while (max >= min) {
   mid = (max + min) / 2;
   // we made the first guess, incrementing step by 1
   step++;
   if (values[mid] == search) {
    System.out.println("Number of steps required for search: " + step);
    return mid;
   } else if (values[mid] > search) {
    // target would be in the left half
    max = (mid - 1);
   } else {
    // target would be in the right half
    min = (mid + 1);
   }
  }
  // if element is not present return -1
  return -1;
 }
}
Output:

Number of steps required for search: 2
Element is present at index: 3

No comments:

Post a Comment