mirror of
https://github.com/jashkenas/coffeescript.git
synced 2026-02-19 03:44:23 -05:00
added binary search example -- chapter 6 of beautiful code
This commit is contained in:
16
examples/beautiful_code/binary_search.coffee
Normal file
16
examples/beautiful_code/binary_search.coffee
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
# Beautiful Code, Chapter 6.
|
||||||
|
# The implementation of binary search that is tested.
|
||||||
|
|
||||||
|
# Return the index of an element in a sorted list. (or -1, if not present)
|
||||||
|
index: list, target =>
|
||||||
|
[low, high]: [0, list.length]
|
||||||
|
while low < high
|
||||||
|
mid: (low + high) >> 1
|
||||||
|
val: list[mid]
|
||||||
|
return mid if val is target
|
||||||
|
if val < target then low: mid + 1 else high: mid
|
||||||
|
return -1
|
||||||
|
|
||||||
|
print(2 is index([10, 20, 30, 40, 50], 30))
|
||||||
|
print(4 is index([-97, 35, 67, 88, 1200], 1200))
|
||||||
|
print(0 is index([0, 45, 70], 0))
|
||||||
Reference in New Issue
Block a user