-
Notifications
You must be signed in to change notification settings - Fork 8
/
BinarySearch_Mojo.mojo
44 lines (33 loc) · 1.03 KB
/
BinarySearch_Mojo.mojo
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
"""Implements basic binary search."""
from Benchmark import Benchmark
from Vector import DynamicVector
alias SIZE = 1000000
alias NUM_WARMUP = 0
alias MAX_ITERS = 100
fn mojo_binary_search(element: Int, array: DynamicVector[Int]) -> Int:
var start = 0
var stop = len(array) - 1
while start <= stop:
let index = (start + stop) // 2
let pivot = array[index]
if pivot == element:
return index
elif pivot > element:
stop = index - 1
elif pivot < element:
start = index + 1
return -1
@parameter # statement runs at compile-time.
fn get_collection() -> DynamicVector[Int]:
var v = DynamicVector[Int](SIZE)
for i in range(SIZE):
v.push_back(i)
return v
fn test_mojo_binary_search() -> F64:
fn test_closure():
_ = mojo_binary_search(SIZE - 1, get_collection())
return F64(Benchmark(NUM_WARMUP, MAX_ITERS).run[test_closure]()) / 1e9
print(
"Average execution time of func in sec ",
test_mojo_binary_search(),
)