Implementation of binary search algorithm in Java collection
Arrays.binarysearch implements a binary search for a specific interval of an ordered array, although we find it very simple, but the reading source does see the best techniques for implementing these libraries, always striving for perfection and efficiency.
the Places worth learning are:(1) boundary check;(2) when seeking the median, use displacement operation instead of X/2;(3) If the found element is not in the array, the return value indicates where it should be inserted, instead of returning directly to 1;
public static int BinarySearch (int[] A, int fromIndex, int toindex,int key) {Rangecheck (A.length, FromIndex, toindex);return BinarySearch0 (A, FromIndex, Toindex, key); }
//Like public version, but without range checks.private static int binarySearch0 (int[] A, int fromIndex, int toindex,int key) {int low = FromIndex;int high = toIndex-1;
While (low <= high) { int mid = (low + high) >>> 1; int midval = A[mid];
if (Midval < key)Low = mid + 1;else if (Midval > key)High = mid-1;Elsereturn mid;//key found } Return-(low + 1); Key not found. } Similarly , there are similar auxiliary functions in collections, but the use of iterators to get elements of a particular position.
public static <T> int BinarySearch (list<? extends Comparable<? Super t>> List, T key) {if (Li St Instanceof Randomaccess | | List.size () < Binarysearch_threshold) return collections. Indexedbinarysearch (list, key); else return collections. Iteratorbinarysearch (list, key); }private static <T> int indexedbinarysearch (list<? extends Comparable<? Super t>> List, T key) { int low = 0; int high = List.size ()-1; while (low <= high) {int mid = (low + high) >>> 1; comparable<? Super T> Midval = List.get (mid); int cmp = Midval.compareto (key); if (CMP < 0) Low = mid + 1; else if (CMP > 0) high = mid-1; else return mid; Key found} return-(low + 1); Key not found} private static <T> int iteratorbinarysearch (LIST<?Extends Comparable<? Super t>> list, T key) {int low = 0; int high = List.size ()-1; listiterator<? Extends Comparable<? Super T>> i = List.listiterator (); while (low <= high) {int mid = (low + high) >>> 1; comparable<? Super T> Midval = Get (i, mid); int cmp = Midval.compareto (key); if (CMP < 0) Low = mid + 1; else if (CMP > 0) high = mid-1; else return mid; Key found} return-(low + 1); Key not Found}/** * Gets the ith element from the given list by repositioning the specified * list listite Rator. */private static <T> t get (listiterator<? extends t> i, int index) {T obj = null; int pos = I.nextindex (); if (POS <= index) {do {obj = I.next ();//List move} while (pos++ < index); } else {do {obj = I.previous (); } while (-pos > Index); } return obj; }
Implementation of binary search algorithm in Java collection