二分法查找
有序数组二分法查找,找到则返回索引,否则返回-1
// 有序数组二分查找5 public int selfQuery() { int[] orderedArray = {1, 1, 2, 3, 3, 5, 7, 9, 9}; int p = 0; int r = orderedArray.length; int q; while (p <= r) { q = (p + r) / 2; if (orderedArray[q] == 5) { return q; } else if (orderedArray[q] < 5) { p = q + 1; } else { r = q - 1; } } return -1; }
二分查找的时间为O(logN)级别