Skip to content

Instantly share code, notes, and snippets.

@jasonsalas
Created July 14, 2022 00:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonsalas/771671b710fb56199e3f6fc362c907d2 to your computer and use it in GitHub Desktop.
Save jasonsalas/771671b710fb56199e3f6fc362c907d2 to your computer and use it in GitHub Desktop.
QuickSort algorithm in Go
package api
import "math/rand"
// QuickSort is a divide-&-conquer algorithm running in O(n log n) time that receives an integer slice
// and returns a sorted slice of integers (h/t: https://gist.github.com/vderyagin/4161347)
func QuickSort(numbers []int) []int {
length := len(numbers)
/* BASE CASE */
if length < 2 {
return numbers
}
/* RECURSIVE CASES */
pivot := numbers[rand.Intn(length)]
left := make([]int, 0, length)
middle := make([]int, 0, length)
right := make([]int, 0, length)
// sort the items in their appropriate slice
for _, item := range numbers {
switch {
case item < pivot:
left = append(left, item)
case item == pivot:
middle = append(middle, item)
case item > pivot:
right = append(right, item)
}
}
// recursively sort the divided slices
left, right = QuickSort(left), QuickSort(right)
// merge into a single sorted slice
left = append(left, middle...)
left = append(left, right...)
return left
}
package api
import (
"fmt"
"reflect"
"testing"
)
var testcases = []struct {
name string
input []int
output []int
}{
{
name: "empty slices",
input: []int{},
output: []int{},
},
{
name: "single-element slices",
input: []int{671},
output: []int{671},
},
{
name: "multi-element slices",
input: []int{64, 12, 32, 4, 23, 11, 98, 5, 43},
output: []int{4, 5, 11, 12, 23, 32, 43, 64, 98},
},
}
func TestQuickSort(t *testing.T) {
t.Run("test cases", func(t *testing.T) {
for _, tc := range testcases {
got := QuickSort(tc.input)
want := tc.output
if !reflect.DeepEqual(got, want) {
t.Errorf("got: %v | want: %v", got, want)
}
}
})
}
func ExampleQuickSort() {
fmt.Println(QuickSort([]int{9, 8, 7, 6, 5, 4, 3, 2, 1}))
// Output: [1 2 3 4 5 6 7 8 9]
}
func BenchmarkQuickSort(b *testing.B) {
for i := 0; i < b.N; i++ {
QuickSort([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment