1. 程式人生 > >基礎算法 - 二分查找

基礎算法 - 二分查找

算法 pub vat bin lower public rst length 查找

public class Main { private static int binary_search(int[] x, int key) { int l = 0, r = x.length - 1; while (l <= r) { int m = (l + r) >>> 1; if (x[m] == key) { return m; } else if (x[m] < key) { ++ l; } else { -- r; } } return -1; } private static int lower_bound(int[] x, int key) { int first = 0; int len = x.length; while (len > 0) { int half = len >>> 1; int m = first + half; if (x[m] < key) { // 右半區 first = m + 1; len -= half + 1; } else { // 左半區 len = half; } } return first; } private static int upper_bound(int[] x, int key) { int first = 0; int len = x.length; while (len > 0) { int half = len >>> 1; int m = first + half; if (x[m] <= key) { // 右半區 first = m + 1; len -= half + 1; } else { // 左半區 len = half; } } return first; } public static void main(String[] args) { } }

基礎算法 - 二分查找