-
-
Save e-kostylov/af9dd71921b8edf7bedc944cc9507773 to your computer and use it in GitHub Desktop.
quick sort implementation in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package qsort | |
import "math/rand" | |
func QuickSort(slice []int) []int { | |
length := len(slice) | |
if length <= 1 { | |
sliceCopy := make([]int, length) | |
copy(sliceCopy, slice) | |
return sliceCopy | |
} | |
m := slice[rand.Intn(length)] | |
less := make([]int, 0, length) | |
middle := make([]int, 0, length) | |
more := make([]int, 0, length) | |
for _, item := range slice { | |
switch { | |
case item < m: | |
less = append(less, item) | |
case item == m: | |
middle = append(middle, item) | |
case item > m: | |
more = append(more, item) | |
} | |
} | |
less, more = QuickSort(less), QuickSort(more) | |
less = append(less, middle...) | |
less = append(less, more...) | |
return less | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package qsort | |
import ( | |
"reflect" | |
"testing" | |
) | |
var testData = []struct { | |
input []int | |
expectedOutput []int | |
}{ | |
{[]int{}, []int{}}, | |
{[]int{42}, []int{42}}, | |
{[]int{42, 23}, []int{23, 42}}, | |
{[]int{23, 42, 32, 64, 12, 4}, []int{4, 12, 23, 32, 42, 64}}, | |
} | |
func TestQuickSort(t *testing.T) { | |
for _, testCase := range testData { | |
actual := QuickSort(testCase.input) | |
expected := testCase.expectedOutput | |
if !reflect.DeepEqual(actual, expected) { | |
t.Errorf("%v != %v\n", actual, expected) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment