## ~telemachus/algorithms

ref: 597d3c5170b0fd3982a2aa1d12e39179f2293bbf algorithms/quickselect.go -rw-r--r-- 1.3 KiB
597d3c51Peter Aronoff Improve the README 1 year, 2 months ago
`                                                                                `
```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```
```package algorithms

// QuickselectL implements quickselect using Lomuto’s partition.
func QuickselectL(xs []int, low, high, nthLowest int) int {
if len(xs) <= 0 || nthLowest > len(xs) {
return -1
}

switch pivotIndex := lomutoPartition(xs, low, high); {
case nthLowest > pivotIndex:
return QuickselectL(xs, pivotIndex+1, high, nthLowest)
case nthLowest < pivotIndex:
return QuickselectL(xs, low, pivotIndex-1, nthLowest)
default:
return xs[nthLowest]
}
}

// QuickselectH implements quickselect using Hoare’s partition.
func QuickselectH(xs []int, low, high, nthLowest int) int {
if len(xs) <= 0 || nthLowest > len(xs) {
return -1
}

switch pivotIndex := hoarePartition(xs, low, high); {
case nthLowest > pivotIndex:
return QuickselectH(xs, pivotIndex+1, high, nthLowest)
case nthLowest < pivotIndex:
return QuickselectH(xs, low, pivotIndex-1, nthLowest)
default:
return xs[nthLowest]
}
}

// QuickselectYB implements quickselect using Stefan Nilsson’s partition.
func QuickselectYB(xs []int, nthLowest int) int {
if len(xs) <= 0 || nthLowest > len(xs) {
return -1
}

pivotValue := yourBasicPivot(xs)
switch low, high := yourBasicPartition(xs, pivotValue); {
case nthLowest <= low:
QuicksortYB(xs[:low])
return xs[nthLowest]
default:
QuicksortYB(xs[high:])
return xs[nthLowest]
}
}
```