Skip to content

Commit 8738fe1

Browse files
committed
Added Quickselect in Go
1 parent cfb6370 commit 8738fe1

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

QuickSelect/Go/QuickSelect.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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() {}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ MiniMaxWithABPruning | :+1: | | | | | | | |
3939
Modified_Binary_Search | | | | :+1: | | | | |
4040
Postman Sort | | | | :+1: | | | | |
4141
Quick Sort | :+1: | :+1: | | | | :+1: | :+1: | :+1: | :+1:
42+
Quick Select | | | | | :+1: | | |
4243
Uniform-cost search | :+1: | | | | | :+1: | :+1: | |
4344
RadixSort | :+1: | :+1: | | | :+1: | | | |
4445
RobinCarp | :+1: | | | | | | | |

0 commit comments

Comments
 (0)