Bifalgorithm post · Computer science one · Sorting

How does binary search work with arrays and lists?

How does binary search work with arrays and lists? (Computer science one · Sorting) — "public static int binarySearch(T[] a, T key, Comparator c) takes an arra…

Ideas in this flowchart

  • Java binary search methods
  • The array-based method accepts an array, a key, and a Comparator.
  • The array elements, key, and comparator use the same type T.
  • When a match is found, the method returns an index containing a matching element.
  • When no match is found, it returns a negative value based on the insertion point.
  • Another version relies on the natural ordering of elements and does not require a Comparator.
  • Elements used by this version must implement the Comparable interface.
  • The Collections class provides a similar binarySearch method for lists.
  • The Collections method accepts a List, a key, and a Comparator.
  • Its behavior is the same as the array-based method; only the collection type differs.
  • Several examples are presented in Code Sample.
Feed/

How does binary search work with arrays and lists?

No cover

Channel

Computer science one

1 page

"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"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.