all repos

scratch @ 753ee96

⭐ me doing recreational ~~drugs~~ programming

scratch/algos/quicksort.go (view raw)

1
package algos
2
3
func partition(inp []int, lo, hi int) int {
4
	pivot := inp[hi] // might result in O(n^2)
5
6
	idx := lo - 1
7
	for i := lo; i < hi; i++ {
8
		if inp[i] <= pivot {
9
			idx++
10
			inp[i], inp[idx] = inp[idx], inp[i]
11
		}
12
	}
13
14
	idx++
15
	inp[hi], inp[idx] = inp[idx], pivot
16
	return idx
17
}
18
19
func qs(inp []int, lo, hi int) {
20
	if lo >= hi {
21
		return
22
	}
23
24
	pivot := partition(inp, lo, hi)
25
	qs(inp, lo, pivot-1)
26
	qs(inp, pivot+1, hi)
27
}
28
29
func QuickSort(input []int) { qs(input, 0, len(input) - 1) }