generated from eigerco/beerus
-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathbinary_search.cairo
69 lines (66 loc) · 1.78 KB
/
binary_search.cairo
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
pub fn binary_search<T, +Copy<T>, +Drop<T>, +PartialEq<T>, +PartialOrd<T>>(
span: Span<T>, val: T,
) -> Option<u32> {
// Initial check
if span.len() == 0 {
return Option::None;
}
let middle = span.len() / 2;
if *span[middle] == val {
return Option::Some(middle);
}
if span.len() == 1 {
return Option::None;
}
if *span[middle] > val {
return binary_search(span.slice(0, middle), val);
}
let mut len = middle;
if span.len() % 2 == 1 {
len += 1;
}
let val = binary_search(span.slice(middle, len), val);
match val {
Option::Some(v) => Option::Some(v + middle),
Option::None => Option::None,
}
}
pub fn binary_search_closest<T, +Copy<T>, +Drop<T>, +PartialOrd<T>>(
span: Span<T>, val: T,
) -> Option<u32> {
// Initial check
if (span.len() == 0) {
return Option::None;
}
let middle = span.len() / 2;
if (*span[middle] <= val && val <= *span[middle]) {
return Option::Some(middle);
}
if (span.len() == 1) {
return Option::None;
}
if (span.len() == 2) {
if (*span[0] <= val && val < *span[1]) {
return Option::Some(0);
} else {
return Option::None;
}
}
let mut len = middle;
if (middle * 2 < span.len()) {
len += 1;
}
if (*span[middle] > val) {
let index = binary_search_closest(span.slice(0, middle + 1), val);
match index {
Option::Some(v) => Option::Some(v),
Option::None => Option::None,
}
} else {
let index = binary_search_closest(span.slice(middle, len), val);
match index {
Option::Some(v) => Option::Some(v + middle),
Option::None => Option::None,
}
}
}