diff --git a/QuickSort/QuickSort.go b/QuickSort/QuickSort.go new file mode 100644 index 0000000..e334be9 --- /dev/null +++ b/QuickSort/QuickSort.go @@ -0,0 +1,24 @@ +package QuickSort + +import ( + "math/rand" +) + +func QuickSort(a []int) []int { + if len(a) < 2 { + return a + } + left, right := 0, len(a)-1 + pivot := rand.Int() % len(a) + a[pivot], a[right] = a[right], a[pivot] + for i, _ := range a { + if a[i] < a[right] { + a[left], a[i] = a[i], a[left] + left++ + } + } + a[left], a[right] = a[right], a[left] + QuickSort(a[:left]) + QuickSort(a[left+1:]) + return a +} \ No newline at end of file diff --git a/QuickSort/QuickSort_test.go b/QuickSort/QuickSort_test.go new file mode 100644 index 0000000..e0462d9 --- /dev/null +++ b/QuickSort/QuickSort_test.go @@ -0,0 +1,24 @@ +package QuickSort +import ( + "math/rand" + "sort" + "testing" + "time" +) + +func TestSelectionSort(t *testing.T) { + random := rand.New(rand.NewSource(time.Now().UnixNano())) + array1 := make([]int, random.Intn(100-10)+10) + for i := range array1 { + array1[i] = random.Intn(100) + } + array2 := make(sort.IntSlice, len(array1)) + copy(array2, array1) + QuickSort(array1) + array2.Sort() + for i := range array1 { + if array1[i] != array2[i] { + t.Fail() + } + } +} diff --git a/README.md b/README.md index 90c81b4..1882109 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ There are several data structures and algorithms implemented in this project. Th - Cocktail Sort - Gnome Sort - Merge Sort +- Quick Sort ## Usage