Java快速写一个二分法查找
public class TestDemo { @org.junit.Test public void test2() { int[] a = new int[]{1, 2, 8, 1, 3}; TestDemo testDemo = new TestDemo(); int search = testDemo.binarySearch(a, 8); System.out.println(search); } public static int binarySearch(int[] array, int value) { int low = 0; int high = array.length - 1; while (low <= high) { int middle = (low + high) >> 1; if (value == array[middle]) { return middle; } if (value > array[middle]) { low = middle + 1; } if (value < array[middle]) { high = middle - 1; } } return -1; } }
=================
快速查找是这样
public static int search(int[] a, int key) { for (int i = 0, length = a.length; i < length; i++) { if (a[i] == key) { return i; } } return -1; }