Answers for "Sorted array of n elements are given, write a program using binary search to search a given element x in A[].Input: No of elements, elements in sorted order and the element to searched in an array.Output: The location where the elemnet is found"

2

binary search java

binary search program in java.
public class BinarySearchExample
{
   public static void binarySearch(int[] arrNumbers, int start, int end, int keyElement)
   {
      int middle = (start + end) / 2;
      while(start <= end)
      {
         if(arrNumbers[middle] < keyElement)
         {
            start = middle + 1;
         }
         else if(arrNumbers[middle] == keyElement)
         {
            System.out.println("Element found at index: " + middle);
            break;
         }
         else
         {
            end = middle - 1;
         }
         middle = (start + end) / 2;
      }
      if(start > end)
      {
         System.out.println("Element not found!");
      }
   }
   public static void main(String[] args)
   {
      int[] arrNumbers = {14,15,16,17,18};
      int keyElement = 16;
      int end = arrNumbers.length - 1;
      binarySearch(arrNumbers, 0, end, keyElement);
   }
}
Posted by: Guest on October-23-2020

Code answers related to "Sorted array of n elements are given, write a program using binary search to search a given element x in A[].Input: No of elements, elements in sorted order and the element to searched in an array.Output: The location where the elemnet is found"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language