The beauty of programming lies in the beauty of algorithms. Let's first look at the binary search algorithm: The Hidden condition: binary search must be ordered, from small to large, or binary search can be performed only after sorting from large to small. Let's look at the code below:
Package com.cn. daming; public class MainActivity {/*** @ param args */public static void main (String [] args) {int [] aInts = new int [] {1, 3, 5, 8, 11,14, 16,24, 37,47, 49,56, 63,83, 223}; // The sorting is from small to large int [] aInts2 = new int [] {322,243,211,156, 98,85, 79,68, 53,47, 38,24, 13, 6, 2}; // The sorting is from large to small // TODO Auto-generated method stub MainActivity main = new MainActivity (); System. out. println ("aInts the reault is:" + main. BinarySearch (aInts, 0, aInts. length, 24); System. out. println ("aInts2 the reault is:" + main. binarySearch2 (aInts2, 0, aInts2.length, 243);} // binary search for private int binarySearch (int [] a, int start, int len, int key) {int high = start + len, low = start-1, guess; while (high-low> 1) {guess = (high + low)/2; if (a [guess] <key) low = guess; else high = guess;} if (high = start + len) r Eturn ~ (Start + len); else if (a [high] = key) return high; else return ~ High;} // binary search from large to small private int binarySearch2 (int [] a, int start, int len, int key) {int high = start + len, low = start-1, guess; while (high-low> 1) {guess = (high + low)/2; if (a [guess]> key) low = guess; else high = guess;} if (high = start + len) return ~ (Start + len); else if (a [high] = key) return high; else return ~ High ;}}