Debian Codegraph @

quickselect.go

raw
1 package sturdyc
2
3 import "time"
4
5 func partition(times []time.Time, low, high int) int {
6 pivot := times[high]
7 i := low
8 for j := low; j < high; j++ {
9 if times[j].Before(pivot) {
10 times[i], times[j] = times[j], times[i]
11 i++
12 }
13 }
14 times[i], times[high] = times[high], times[i]
15 return i
16 }
17
18 func quickSelect(times []time.Time, low, high, k int) time.Time {
19 if low < high {
20 pi := partition(times, low, high)
21 if pi == k {
22 return times[pi]
23 } else if pi < k {
24 return quickSelect(times, pi+1, high, k)
25 }
26 return quickSelect(times, low, pi-1, k)
27 }
28
29 // Base case for single element
30 return times[low]
31 }
32
33 // FindCutoff returns the time that is the k-th smallest time in the slice.
34 func FindCutoff(times []time.Time, percentile float64) time.Time {
35 if len(times) == 0 {
36 return time.Time{}
37 }
38 if percentile < 0 || percentile > 1 {
39 return time.Time{}
40 }
41
42 n := len(times)
43 // Calculate the index for the given percentile
44 k := int(float64(n) * percentile)
45 // Adjust if k equals the length of the slice
46 if k == n {
47 k--
48 }
49 return quickSelect(times, 0, n-1, k)
50 }