nx_binary_search_test.nx source
↩ module page · 49 lines · 1527 B
1// nx_binary_search_test.nx -- canonical exercise of search + lower_bound.
2
3import "nx_syscalls.nx"
4import "nx_binary_search.nx"
5
6func main() -> nx_int {
7 let arr: *nx_int = (sys_mmap(80)) as *nx_int
8 arr[0] = 2
9 arr[1] = 5
10 arr[2] = 7
11 arr[3] = 11
12 arr[4] = 13
13 arr[5] = 17
14 arr[6] = 19
15 arr[7] = 23
16 arr[8] = 29
17 arr[9] = 31
18 let n: nx_idx = 10
19
20 // ===== nx_binary_search =====
21 // #1 first element
22 if nx_binary_search(arr, n, 2) != 0 { return 1 }
23 // #2 last element
24 if nx_binary_search(arr, n, 31) != 9 { return 2 }
25 // #3 middle element
26 if nx_binary_search(arr, n, 13) != 4 { return 3 }
27 // #4 key below all
28 if nx_binary_search(arr, n, 1) != -1 { return 4 }
29 // #5 key above all
30 if nx_binary_search(arr, n, 100) != -1 { return 5 }
31 // #6 key absent but in range
32 if nx_binary_search(arr, n, 14) != -1 { return 6 }
33 // #7 empty array
34 if nx_binary_search(arr, 0, 5) != -1 { return 7 }
35
36 // ===== nx_binary_search_lower_bound =====
37 // #8 exact match -> the match index
38 if nx_binary_search_lower_bound(arr, n, 11) != 3 { return 8 }
39 // #9 between elements -> first >=
40 if nx_binary_search_lower_bound(arr, n, 14) != 5 { return 9 }
41 // #10 below all -> 0
42 if nx_binary_search_lower_bound(arr, n, 1) != 0 { return 10 }
43 // #11 above all -> n
44 if nx_binary_search_lower_bound(arr, n, 100) != n { return 11 }
45 // #12 empty -> 0
46 if nx_binary_search_lower_bound(arr, 0, 5) != 0 { return 12 }
47
48 return 0
49}