Concept
How does binary search work with arrays and lists?
"public static <T> int binarySearch(T[] a, T key, Comparator<T> c) takes an array of elements as well as a key and a Comparator, all of the same type T. It returns an integer representing the index at which it finds a matching element; there is no guarantee that the first element in the sorted list is returned. If no match is found, then the method returns something negative. It actually returns a negative value corresponding to the insertion point at which the element would be if it had existed. Another version has the same behavior but can be called without a Comparator, relying instead on the natural ordering of elements. For this variation, the type of elements must implement the Comparable interface. The Collections class provides a similar method, public static <T> int binarySearch(List<T> list, T key, Comparator<T> c). The only difference is that the method takes a List instead of an array. Otherwise, the behavior is the same. We present several examples in Code Sample"
Related Ideas
- How does Java perform binary searches on arrays and lists?ComputerScienceOne · Sorted Collections
- What are the requirements for using binary search in Java?ComputerScienceOne · Searching
- How does a Comparator determine the order of two elements?ComputerScienceOne · Comparators
- What is the difference between Comparable and Comparator in Java?ComputerScienceOne · Comparators
- Which recursive and iterative binary search algorithms are listed?ComputerScienceOne · Linear Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
- How can a Comparator sort Student objects by GPA?ComputerScienceOne · Searching
- How do Java collections perform a linear search?ComputerScienceOne · Searching
- How do sorted collections maintain element order?ComputerScienceOne · Sorting