Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.Arrays;
- import java.util.Scanner;
- public class ImplementRecursiveBinarySearch {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- int element = sc.nextInt();
- sc.nextLine();
- Integer[] array = Arrays.stream(sc.nextLine().split("\\s+")).map(Integer::parseInt).toArray(Integer[]::new);
- Arrays.sort(array,(e1,e2) -> e1.compareTo(e2));
- int elementIndex = BinarySearch(array,element,0,array.length);
- System.out.println(elementIndex); //Return the index of the element, or -1, if the element is not found.
- }
- private static int BinarySearch(Integer[] array, int element, int left, int right) {
- if (element > array[right - 1] || element < array[left]){
- return -1;
- }
- int mid = (left + right) / 2;
- if (element > array[mid]){
- return BinarySearch(array, element, mid + 1, right);
- }else if (element < array[mid]){
- return BinarySearch(array, element, left, mid - 1);
- }else if(element == array[mid]){
- return mid;
- }
- return -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement