Advertisement
ivanov_ivan

ImplementRecursiveBinarySearch

Feb 11th, 2016
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.20 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.Arrays;
  4. import java.util.Scanner;
  5.  
  6. public class ImplementRecursiveBinarySearch {
  7.     public static void main(String[] args) {
  8.  
  9.         Scanner sc = new Scanner(System.in);
  10.  
  11.         int element = sc.nextInt();
  12.  
  13.         sc.nextLine();
  14.  
  15.         Integer[] array = Arrays.stream(sc.nextLine().split("\\s+")).map(Integer::parseInt).toArray(Integer[]::new);
  16.  
  17.         Arrays.sort(array,(e1,e2) -> e1.compareTo(e2));
  18.  
  19.         int elementIndex = BinarySearch(array,element,0,array.length);
  20.  
  21.         System.out.println(elementIndex); //Return the index of the element, or -1, if the element is not found.
  22.  
  23.     }
  24.  
  25.     private static int BinarySearch(Integer[] array, int element, int left, int right) {
  26.  
  27.         if (element > array[right - 1] || element < array[left]){
  28.  
  29.             return -1;
  30.         }
  31.  
  32.         int mid = (left + right) / 2;
  33.  
  34.         if (element > array[mid]){
  35.  
  36.             return BinarySearch(array, element, mid + 1, right);
  37.  
  38.         }else if (element < array[mid]){
  39.  
  40.             return BinarySearch(array, element, left, mid - 1);
  41.  
  42.         }else if(element == array[mid]){
  43.  
  44.             return mid;
  45.         }
  46.  
  47.         return -1;
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement