Created
November 4, 2019 19:26
-
-
Save MSevey/7a20a05731706a3ce9706fa3053863dd to your computer and use it in GitHub Desktop.
Easy Quick Sort
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 main | |
import ( | |
"fmt" | |
"gitlab.com/NebulousLabs/fastrand" | |
) | |
func main() { | |
slice := generateIntSlice(20) | |
fmt.Printf("Unsorted Slice:\n%v\n", slice) | |
fmt.Printf("Sorted Slice:\n%v\n", quickSort(slice)) | |
} | |
// generateIntSlice creates a random int slice of the input size using the | |
// fastrand package Intn | |
func generateIntSlice(size int) []int { | |
// Initialize int slice, size and capacity | |
slice := make([]int, size, size) | |
// create random slice | |
for i := 0; i < size; i++ { | |
slice[i] = fastrand.Intn(200) | |
} | |
return slice | |
} | |
// quickSort sorts a slice in place using a pivot element | |
func quickSort(arr []int) []int { | |
if len(arr) <= 1 { | |
return arr | |
} | |
// Set the first element as the pivot | |
pivot := arr[0] | |
var smaller, larger []int | |
for i := 1; i < len(arr); i++ { | |
if arr[i] < pivot { | |
smaller = append(smaller, arr[i]) | |
} else { | |
larger = append(larger, arr[i]) | |
} | |
} | |
// Call quicksort on two halves | |
smallerSorted := quickSort(smaller) | |
largerSorted := quickSort(larger) | |
return append(append(smallerSorted, pivot), largerSorted...) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment