-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-search.red
45 lines (38 loc) · 1.1 KB
/
binary-search.red
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Red [
Title: "binary searching"
File: %binary-search.red
Author: "WayneCui"
Date: "2019-01-18"
Purpose: {binary searching for an integer in a sorted block of integers.
See: https://algs4.cs.princeton.edu/11model/BinarySearch.java.html}
Version: 0.0.1
]
binary-search: function [a [series!] key [integer!]][
low: 1
high: (length? a)
while [ low <= high ] [
mid: (low + high) >>> 1
; mid: (high - low) / 2 + low
mid-val: a/(mid)
case [
mid-val < key [ low: mid + 1]
mid-val > key [ high: mid - 1]
mid-val = key [ return mid ] ; key found
]
]
negate (low) ; key not found. Also as -(insertion point), following java: Collections#binarySearch
]
main: function [][
blk: [1 3 5 7 9]
print binary-search blk 1
print binary-search blk 2
print binary-search blk 3
print binary-search blk 4
print binary-search blk 5
print binary-search blk 6
print binary-search blk 7
print binary-search blk 8
print binary-search blk 9
print binary-search blk 10
]
main