φ(i,j) = | ( | k ∈ t[0...n[ ⇒ k ∈ t[i...j[ | ) |
static boolean search(int [] t, int k) { int low = 0 ; int high = t.length ; // 0 ≤ low ≤ high ≤ n ∧ φ(low, high) while (high-low > 0) { // 0 ≤ low < high ≤ n ∧ φ(low, high) int m = (low+high) / 2 ; // 0 ≤ low ≤ m < high ≤ n ∧ φ(low, high) if (k < t[m]) { // φ(low,m) ∧ 0 ≤ low ≤ m < high ≤ n high = m ; // φ(low, high) ∧ 0 ≤ low ≤ high < n } else if (k > t[m]) { // φ(m+1,high) ∧ 0 ≤ low ≤ m < high ≤ n ∧ φ(low, high) low = m+1 ; // φ(low, high) ∧ 0 < low ≤ high ≤ n } else { // t[m] = k return true ; // Rien~! } // φ(low, high) ∧ 0 ≤ low ≤ high ≤ n } // 0 ≤ low = high ≤ n ∧ φ(low,high) return false ; } |
static boolean search(int [] t, int k) { int low = 0 ; int high = t.length-1 ; while (low <= high) { int m = (low+high) / 2 ; if (k < t[m]) { high = m-1 ; } else if (k > t[m]) { low = m+1 ; } else { return true ; } } return false ; } |