-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathbinary.jule
80 lines (75 loc) · 2.61 KB
/
binary.jule
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
70
71
72
73
74
75
76
77
78
79
80
// Search for target within a sorted array by repeatedly dividing the array in half and comparing the midpoint with the target.
// This function uses recursive call to itself.
// If a target is found, the index of the target is returned. Else the function throws exceptional with Error.NotFound.
fn Binary(array: []int, target: int, lowIndex: int, highIndex: int)!: int {
if highIndex < lowIndex || len(array) == 0 {
error(Error.NotFound)
}
mid := int(lowIndex + (highIndex-lowIndex)/2)
if array[mid] > target {
ret Binary(array, target, lowIndex, mid-1) else { error(error) }
} else if array[mid] < target {
ret Binary(array, target, mid+1, highIndex) else { error(error) }
} else {
ret mid
}
}
// Search for target within a sorted array by repeatedly dividing the array in half and comparing the midpoint with the target.
// Unlike Binary, this function uses iterative method and not recursive.
// If a target is found, the index of the target is returned. Else the function throws exceptional with Error.NotFound.
fn BinaryIterative(array: []int, target: int)!: int {
mut startIndex := 0
mut endIndex := len(array) - 1
mut mid := 0
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] > target {
endIndex = mid - 1
} else if array[mid] < target {
startIndex = mid + 1
} else {
ret mid
}
}
error(Error.NotFound)
}
// Returns index to the first element in the range [0, len(array)-1] that is not less than (i.e. greater or equal to) target.
// Throws exceptional with Error.NotFound if no such element is found.
fn LowerBound(array: []int, target: int)!: int {
mut startIndex := 0
mut endIndex := len(array) - 1
mut mid := 0
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] < target {
startIndex = mid + 1
} else {
endIndex = mid - 1
}
}
// when target greater than every element in array, startIndex will out of bounds
if startIndex >= len(array) {
error(Error.NotFound)
}
ret startIndex
}
// Returns index to the first element in the range [lowIndex, len(array)-1] that is greater than target.
// Throws exceptional with Error.NotFound if no such element is found.
fn UpperBound(array: []int, target: int)!: int {
mut startIndex := 0
mut endIndex := len(array) - 1
mut mid := 0
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] > target {
endIndex = mid - 1
} else {
startIndex = mid + 1
}
}
// when target greater or equal than every element in array, startIndex will out of bounds
if startIndex >= len(array) {
error(Error.NotFound)
}
ret startIndex
}