From 380d901739c43b8c93d23f628fa6b247db14b64c Mon Sep 17 00:00:00 2001 From: alastairruhm Date: Wed, 11 Apr 2018 16:01:31 +0800 Subject: [PATCH] quick sort --- algorithm/sorting/quick-sort/quick_sort.go | 26 +++++++++++++++++++ .../sorting/quick-sort/quick_sort_test.go | 26 +++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 algorithm/sorting/quick-sort/quick_sort.go create mode 100644 algorithm/sorting/quick-sort/quick_sort_test.go diff --git a/algorithm/sorting/quick-sort/quick_sort.go b/algorithm/sorting/quick-sort/quick_sort.go new file mode 100644 index 0000000..e1a3279 --- /dev/null +++ b/algorithm/sorting/quick-sort/quick_sort.go @@ -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 +} diff --git a/algorithm/sorting/quick-sort/quick_sort_test.go b/algorithm/sorting/quick-sort/quick_sort_test.go new file mode 100644 index 0000000..40e486d --- /dev/null +++ b/algorithm/sorting/quick-sort/quick_sort_test.go @@ -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) + } + }) + }) +}