1+ package main
2+
3+ import (
4+ "math/rand"
5+ )
6+
7+ func quickselect (list []int , item_index int ) int {
8+ return selec (list ,0 , len (list ) - 1 , item_index )
9+ }
10+
11+ func partition (list []int , left int , right int , pivotIndex int ) int {
12+ pivotValue := list [pivotIndex ]
13+
14+ // move pivot to end
15+ list [pivotIndex ], list [right ] = list [right ], list [pivotIndex ]
16+
17+ storeIndex := left
18+
19+ for i := left ; i < right ; i ++ {
20+ if list [i ] < pivotValue {
21+ // move pivot to its final place
22+ list [storeIndex ], list [i ] = list [i ], list [storeIndex ]
23+ storeIndex += 1
24+ }
25+ }
26+ list [right ], list [storeIndex ] = list [storeIndex ], list [right ]
27+
28+ return storeIndex
29+ }
30+
31+ func selec (list []int , left int , right int , k int ) int {
32+
33+ if left == right {
34+ return list [left ]
35+ }
36+
37+ pivotIndex := rand .Intn (right )
38+ // the pivot in its final sorted position
39+ pivotIndex = partition (list , left , right , pivotIndex )
40+
41+ if k == pivotIndex {
42+ return list [k ]
43+ } else if k < pivotIndex {
44+ return selec (list , left , pivotIndex - 1 , k )
45+ } else {
46+ return selec (list , pivotIndex + 1 , right , k )
47+ }
48+ }
49+
50+ func main () {}
0 commit comments