Module: CodeCook::Find
- Defined in:
- 手写代码必备手册(Ruby版).rb
Overview
第六章 查找
Defined Under Namespace
Modules: HashSet
Class Method Summary (collapse)
-
+ (Integer) binary_search(a = [], x)
6.1 二分查找/折半查找 有序顺序表的折半查找算法.
Class Method Details
+ (Integer) binary_search(a = [], x)
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
# File '手写代码必备手册(Ruby版).rb', line 180 def binary_search(a=[], x) # 查找前先排序 p a.sort! left = 0 right = a.size - 1 while left <= right mid = left + (right - left)/2 if x > a[mid] left = mid + 1 elsif x < a[mid] right = mid - 1; else return mid end end return -(left + 1) end |