3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScriptで二分探索(UpperBound, LowerBound)をしてみる

Last updated at Posted at 2020-05-22

:book: LowerBound,UpperBoundとは

二分探索の一種のようなもの。

-lowerboundは、指定された要素以上の値が現れる最初の位置を返す
-upperboundは、指定された要素より大きい値が現れる最初の位置を返す

分かりにくいので具体例
前提として二分探索と同じくソート済みの配列に対して使います

[2, 4, 20, 22, 30, 34]

こんな配列があったします。
例えばlowerBound(15)で得られるのは「2」です。
他にはupperBound(15)で得られるのは「3」です。

boundっていう名前の通り境界の位置を返してくるイメージだと分かりやすいかもしれません。

:computer: コード

const lowerBound = (arr, n) => {
    let first = 0, last = arr.length - 1, middle;
    while (first <= last) {
        middle = 0 | (first + last) / 2;
        if (arr[middle] < n) first = middle + 1;
        else last = middle - 1;
    }
    return first;
}

const upperBound = (arr, n) => {
    let first = 0, last = arr.length - 1, middle;
    while (first <= last) {
        middle = 0 | (first + last) / 2;
        if (arr[middle] <= n) first = middle + 1;
        else last = middle - 1;
    }
    return first;
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?