Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.39 KB | None | 0 0
  1. /**
  2.   227        * Searches the specified list for the specified object using the binary
  3.   228        * search algorithm.  The list must be sorted into ascending order
  4.   229        * according to the {@linkplain Comparable natural ordering} of its
  5.   230        * elements (as by the {@link #sort(List)} method) prior to making this
  6.   231        * call.  If it is not sorted, the results are undefined.  If the list
  7.   232        * contains multiple elements equal to the specified object, there is no
  8.   233        * guarantee which one will be found.
  9.   234        *
  10.   235        * <p>This method runs in log(n) time for a "random access" list (which
  11.   236        * provides near-constant-time positional access).  If the specified list
  12.   237        * does not implement the {@link RandomAccess} interface and is large,
  13.   238        * this method will do an iterator-based binary search that performs
  14.   239        * O(n) link traversals and O(log n) element comparisons.
  15.   240        *
  16.   241        * @param  list the list to be searched.
  17.   242        * @param  key the key to be searched for.
  18.   243        * @return the index of the search key, if it is contained in the list;
  19.   244        *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
  20.   245        *         <i>insertion point</i> is defined as the point at which the
  21.   246        *         key would be inserted into the list: the index of the first
  22.   247        *         element greater than the key, or <tt>list.size()</tt> if all
  23.   248        *         elements in the list are less than the specified key.  Note
  24.   249        *         that this guarantees that the return value will be &gt;= 0 if
  25.   250        *         and only if the key is found.
  26.   251        * @throws ClassCastException if the list contains elements that are not
  27.   252        *         <i>mutually comparable</i> (for example, strings and
  28.   253        *         integers), or the search key is not mutually comparable
  29.   254        *         with the elements of the list.
  30.   255        */
  31.   256       public static <T>
  32.   257       int binarySearch(List<? extends Comparable<? super T>> list, T key) {
  33.   258           if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
  34.   259               return Collections.indexedBinarySearch(list, key);
  35.   260           else
  36.   261               return Collections.iteratorBinarySearch(list, key);
  37.   262       }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement