Binary search for minimum and maximum element. Java
-
My method finds what index the number is.
I need him to look for what number is assigned to the minimum index and what the maximum.
int position;
position = (first + last) / 2;
while ((array[position] != item) && (first <= last)) {
if (array[position] > item) {
last = position - 1;
} else {
first = position + 1;
}
position = (first + last) / 2;
}
if (first <= last) {
System.out.println(item + " является " + ++position + " элементом в массиве");
}
-
Only if the input area is fragmented and contains recurrent elements, a binary search can first determine the existence of the required element and then can be found for indices on the left and right.
More generally, it is easier to filter the O(N) indices and return the first and last indices.
static int[] firstAndLastIndexes(int x, int ... arr) { int[] indexes = IntStream.range(0, arr.length) .filter(i -> arr[i] == x) .toArray(); if (indexes.length < 1) { return new int[]{-1, -1}; } return new int[]{indexes[0], indexes[indexes.length - 1]}; }