Binary search in Java Searching in a descending sorted array
阿新 • • 發佈:2020-08-14
The method described in the theory performs binary search for arrays sorted in ascending order. Your task here is to modify the method such that:
- it allows searching in descending sorted arrays;
- it returns the first index of a target element from the beginning of the array (the leftmost index).
Sample Input 1:
15
17 17 16 15 15 15 15 14 14
Sample Output 1:
3
Sample Input 2:
2
3 3 3 3 3 1 1 1 0
Sample Output 2:
-1
Sample Input 3:
22
40 31 22 22 22 22 22 22
Sample Output 3:
2
import java.util.ArrayList; import java.util.Scanner; public class Main { /* Modify this method */ public static int binarySearch(int elem, int[] array) { int left = -1; int right = array.length; while (left < right - 1) { int mid = left + (right - left) / 2; if (array[mid] > elem) { left = mid; } else { right = mid; } } if (array[right] == elem) { return right; } else { return -1; } } /* Do not change code below */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int elem = scanner.nextInt(); ArrayList<Integer> list = new ArrayList<>(); while (scanner.hasNextInt()) { list.add(scanner.nextInt()); } int[] array = new int[list.size()]; for (int i = 0; i < array.length; i++) { array[i] = list.get(i); } System.out.println(binarySearch(elem, array)); } }