Skip to content

Commit

Permalink
quick sort
Browse files Browse the repository at this point in the history
  • Loading branch information
alastairruhm committed Apr 11, 2018
1 parent c1c8cbb commit 380d901
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
26 changes: 26 additions & 0 deletions algorithm/sorting/quick-sort/quick_sort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package quicksort

// QuickSort ...
func QuickSort(array []int) []int {
var sorted []int
if len(array) < 2 { // array is sorted if the length is 0 or 1,
sorted = array
// return array
} else {
pivot := array[0] // pivot value use to compare
var less []int
var greater []int
for _, e := range array[1:] {
if e <= pivot {
less = append(less, e)
} else {
greater = append(greater, e)
}
}
sorted = append(sorted, QuickSort(less)...)
sorted = append(sorted, pivot)
sorted = append(sorted, QuickSort(greater)...)
// return sorted
}
return sorted
}
26 changes: 26 additions & 0 deletions algorithm/sorting/quick-sort/quick_sort_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package quicksort

import (
"testing"

. "github.com/smartystreets/goconvey/convey"
)

func TestQuickSort(t *testing.T) {
var cases = []struct {
input []int
expected []int
}{
{[]int{5, 2, 1, 4, 3}, []int{1, 2, 3, 4, 5}},
{[]int{1, 5, 2, 4, 3}, []int{1, 2, 3, 4, 5}},
}
// Only pass t into top-level Convey calls
Convey("Quick Sort", t, func() {
Convey("ok", func() {
for _, c := range cases {
o := QuickSort(c.input)
So(o, ShouldResemble, c.expected)
}
})
})
}

0 comments on commit 380d901

Please sign in to comment.