-
Notifications
You must be signed in to change notification settings - Fork 0
/
selection_nth.go
87 lines (65 loc) · 1.52 KB
/
selection_nth.go
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
81
82
83
84
85
86
87
package mysorts
// SelectNth select n-th (n start by 1) order statistic from the input array,
// return the index of the n-th element if succeed, -1 if failed.
func SelectNth(in []int, n int) int {
if n <= 0 || n > len(in) {
return -1
}
return selectNthImpl(subArray(in), n-1, 0, len(in)-1)
}
func selectNthImpl(in subArray, i, p, r int) int {
medianV := selectNthMedianImpl(in, p, r)
// partition by medianV
q := partitionByX(in, medianV, p, r)
if q == i {
return q
}
if q > i {
return selectNthImpl(in, i, p, q-1)
}
return selectNthImpl(in, i, q+1, r)
}
// partition by x
func partitionByX(in subArray, x, p, r int) int {
k := p - 1
xIndex := -1
for j := p; j <= r; j++ {
if in[j] <= x {
k++
if in[j] == x {
xIndex = k //at least 1 element value == x
}
if k != j {
in.Swap(k, j)
}
}
}
in.Swap(xIndex, k)
return k
}
func selectNthMedianImpl(in subArray, p, r int) int {
piece := 5
sparseArray := subArray{}
for j := p; j <= r; j += piece {
median := piece / 2
jr := j + piece
if jr > r+1 {
jr = r + 1
median = (jr - j) / 2
}
// sort each array
s := (subArray)(in[j:jr])
InsertionSort(s)
sparseArray = append(sparseArray, s[median])
}
if sparseArray.Len() > 1 {
return selectNthMedianImpl(sparseArray, 0, sparseArray.Len()-1)
}
return sparseArray[0]
}
type subArray []int
func (s subArray) Len() int { return len(s) }
func (s subArray) Less(i, j int) bool { return s[i] < s[j] }
func (s subArray) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}