Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reasoning behind java.util.Collections.binarySearch return value, when the key isn't found? [duplicate]

Quoting from the docs it says that java.util.Collections.binarySearch(List<? extends Comparable<? super T>> list, T key) returns...

the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size() if all elements in the list are less than the specified key...

My question is, what significance (if any) does the theorem (-(insertion point) - 1) have such that it's the return value when a key isn't found? Why not just return insertion point for instance?

like image 454
asherbret Avatar asked Jun 28 '15 19:06

asherbret


People also ask

What does collections binarySearch return if not found?

Collections. binarySearch(). This method requires two parameters i.e. the list in which binary search is to be performed and the element that is to be searched. It returns the index of the element if it is in the list and returns -1 if it is not in the list.

What does Collections binarySearch return?

The binarySearch() is an inbuilt method of Java Collections class which returns the position of the object in a sorted list.

How to use binary Search from java Collections?

binarySearch() method is a java. util. Collections class method that returns position of an object in a sorted list. // Returns index of key in sorted list sorted in // ascending order public static int binarySearch(List slist, T key) // Returns index of key in sorted list sorted in // order defined by Comparator c.

What is the Collections class in java?

The Collections class Java Collections class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection, and a few other odds and ends.


1 Answers

First thing, if the element is not found, a negative value must be returned according to the documetation, or you cannot distinguish between found and not found.

Ok, so why not just -insertion point? Imagine if the insertion point is 0 (the searched element is smaller than all existing ones), then that logic would break - not found would return a non-negative number. Hence the extra -1.

Ok, so why not just -1 always?

Because knowing the insertion point of a non-match in a sorted list is useful to find answers to questions such as:

What is the next element that is bigger than the one I ask for?

and

How many elements are larger than the one I (didn't) find?

And, the way binary search works, the algorithm knows this index when it terminates, so why not share it when it costs nothing extra?

like image 200
K Erlandsson Avatar answered Sep 23 '22 15:09

K Erlandsson