'Binary search implementation in Java
if(this.passenger.validatePassengerDetails() && checkEngine() && this.capacity <= 200) {
if(Arrays.binarySearch(airlineClassAir, "flightClass") >=0 && (destination.equals("tx") || destination.equals("ca"))) {
int index = Arrays.binarySearch(airlineClassAir, "flightClass");
int amount = airlineClassPriceAir[index];
double totalAmount = amount + amount* (18/100);
I am trying to understand how the binary search is being implemented here? Can someone explain if(Arrays.binarySearch(airlineClassAir, "flightless") >=0 is trying to do here?
Solution 1:[1]
As documented on Arrays.binarySearch(Object[], Object) (emphasis mine):
Returns:
index of the search key, if it is contained in the array; otherwise,(-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, ora.lengthif all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
In other words, you compare with >= 0 to check if the value exists in the array. Be aware though of the requirement that the array must be sorted (an earlier version of your answer showed it wasn't sorted), otherwise the behaviour is undefined: it might find the item, or it might return a negative value even if the value exists.
To explicitly answer the question, the expression Arrays.binarySearch(airlineClassAir, "flightless") >=0 will be true if airlineClassAir contains the string "flightless", and false otherwise (assuming it is sorted, otherwise it might return false even if the value is in the array).
Personally, if your requirement is to check for existence and there are no other uses of that array, I would use a Set<String> and use its contains method instead, as that expresses intent more clearly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
