Skip to content

Instantly share code, notes, and snippets.

@lzakharov
Last active January 6, 2020 06:17
Show Gist options
  • Select an option

  • Save lzakharov/e5a4e25ffb1b3d0ae1e8decef83189fa to your computer and use it in GitHub Desktop.

Select an option

Save lzakharov/e5a4e25ffb1b3d0ae1e8decef83189fa to your computer and use it in GitHub Desktop.
Quicksort in Go
package quicksort
import (
"math/rand"
"sync"
)
func Sort(xs []int) []int {
if len(xs) < 2 {
return xs
}
left, right := 0, len(xs)-1
middle := rand.Intn(len(xs))
xs[middle], xs[right] = xs[right], xs[middle]
for i := range xs {
if xs[i] < xs[right] {
xs[left], xs[i] = xs[i], xs[left]
left++
}
}
xs[left], xs[right] = xs[right], xs[left]
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
Sort(xs[:left])
wg.Done()
}()
go func() {
Sort(xs[left:])
wg.Done()
}()
wg.Wait()
return xs
}
package quicksort
import (
"reflect"
"testing"
)
func TestSort(t *testing.T) {
type args struct {
xs []int
}
tests := []struct {
name string
args args
want []int
}{
{
name: "simple",
args: args{
xs: []int{3, 1, 5, 2, 4},
},
want: []int{1, 2, 3, 4, 5},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Sort(tt.args.xs); !reflect.DeepEqual(got, tt.want) {
t.Errorf("Sort() = %v, want %v", got, tt.want)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment