How do I find out if one of several values is located in an array in Java?

Viewed 66

I am new to Java and trying to do the following:

Given an integer array, if an integer in the array is between 70 and 79, print "Yes". Otherwise, print "no".

Here is my code so far:

import java.util.Arrays;

int temperatures[] = {45, 70, 71, 67}; //create array 
Arrays.sort(temperatures); //sort temperatures
int key = 70; //define key to be searched
int result = Arrays.binarySearch(temperatures,key);

I know this will find me the 70 value that's in the temperatures array, but what's the best way to use binarySearch to see if ANY value in the 70s is in the array?

3 Answers

We can make use of the fact that Arrays.binarySearch returns -(insertion point) - 1 if the element is not found. We can find 70 using binarySearch. If it is found, great! Otherwise, look at the insertion point. If it is out of range, then every element is smaller than 70. Otherwise, the insertion point will be the smallest element in the array that is bigger than 70. If that is bigger than or equal to 80, we know there are no numbers in the range 70-79 in the array.

If you just invert every condition in he explanation above, you get:

int result = Arrays.binarySearch(temperatures, 70);
if (result >= 0 || // we found 70, or
   (-result - 1 < temperatures.length && // insertion point in range, and 
       temperatures[-result - 1] < 80) // insertion point less than 80
) {
  System.out.println("There is at least one temperature in the array that is within the range 70-79");
}

Set a boolean to false, iterate through the array starting at the first element, check each element while the boolean is false and the index is less than the length of the array. If an element is between 70 and 79, set the boolean to true. Check the boolean, and print yes if the boolean is true.

binarySearch allows you to specify a Comparator, which defines which item is larger and when they are equal.

If we use a comparator which compares the numbers divided by 10, then we can use binarySearch.

import java.util.Arrays;
import java.util.Comparator;

public class SO69217093 {

    public static void main(String[] args) {
        Comparator<Integer> comparator = new Comparator<Integer>() {
            public int compare(Integer o1, Integer o2) {
                int decade1 = o1 / 10;
                int decade2 = o2 / 10;
                return Integer.compare(decade1, decade2);
            }
        };
        Integer temperatures[] = {45, 70, 71, 67}; //create array
        Arrays.sort(temperatures); //sort temperatures
        int key = 70; //define key to be searched
        int result = Arrays.binarySearch(temperatures,70, comparator);
        int result2 = Arrays.binarySearch(temperatures,80, comparator);
    }
}

Because Comparator works on objects, not primitives, you'll need to use an array of Integer.

Related