二元搜尋 Binary Search


用二元搜尋法在1~6中搜尋4


疊代

function search(list, target)
    var left = 0, right = list.length - 1
    while left <= right
        var middle = 取出list中點
        if list[middle] == target
            return middle
        // 比目標大,再搜索左半邊
        else if list[middle] > target
            right = middle - 1
        // 比目標小,再搜索右半邊
        else if list[middle] < target
            left = middle + 1
        end if
    end while
    return -1
end function

遞迴

function search(list, target, left, right)
    if left > right
        return -1
    end
    var middle = 取出list中點
    if list[middle] == target
        return middle
    // 比目標大,再搜索左半邊
    else if list[middle] > target
        return search(list, target, left, middle - 1)
    // 比目標小,再搜索右半邊
    else if list[middle] < target
        return search(list, target, middle + 1, right)
    end if
    return 
end function

參考資料 http://emn178.pixnet.net/blog/post/88780407-%E4%BA%8C%E5%85%83%E6%90%9C%E7%B4%A2%E6%B3%95%28binary-search%29

results matching ""

    No results matching ""