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
|
package algo
import (
"math/rand"
"sort"
"github.com/dropbox/godropbox/errors"
)
// [left, right]
func Partition(array sort.Interface, left int, right int,
pivotIndex int) (int, error) {
if pivotIndex < left || pivotIndex > right {
return -1, errors.New("Pivot index out of range")
}
if left < 0 || right >= array.Len() {
return -1, errors.New("Array index out of range")
}
lastIndex := right
array.Swap(pivotIndex, lastIndex)
leftIndex := left
for i := left; i < lastIndex; i++ {
if array.Less(i, lastIndex) {
array.Swap(leftIndex, i)
leftIndex++
}
}
array.Swap(leftIndex, lastIndex)
return leftIndex, nil
}
// k is started from 1
func QuickSelect(array sort.Interface, k int) error {
if k <= 0 || k > array.Len() {
return errors.New("Parameter k is invalid")
}
k--
left := 0
right := array.Len() - 1
for {
if left == right {
return nil
}
pivotIndex := left + rand.Intn(right-left+1)
pivotIndex, err := Partition(array, left, right, pivotIndex)
if err != nil {
return errors.Wrap(err, "Partition returns error")
}
if k == pivotIndex {
return nil
} else if k < pivotIndex {
right = pivotIndex - 1
} else {
left = pivotIndex + 1
}
}
}
|