Skip to content

Instantly share code, notes, and snippets.

@dnutiu
Created April 28, 2018 10:32
Show Gist options
  • Save dnutiu/e7519b6014b68403460d24912b022bd2 to your computer and use it in GitHub Desktop.
Save dnutiu/e7519b6014b68403460d24912b022bd2 to your computer and use it in GitHub Desktop.
Quicksort algorithm in GO
package main
import "fmt"
func quicksort(slice []int) ([]int) {
length := len(slice)
// The array is considered sorted if it contains only one element.
if length < 2 {
return slice
}
// Picking a pivot.
pivot := slice[0]
// Partitioning the array into sub-arrays.
var left []int
var right []int
for _, v := range slice[1:] {
if v <= pivot {
left = append(left, v)
}
}
for _, v := range slice[1:] {
if v > pivot {
right = append(right, v)
}
}
right = quicksort(right)
left = quicksort(left)
// Concatenating left, pivot and right.
left = append(left, pivot)
left = append(left, right...)
return left
}
func main() {
var slice = []int{12, 1, 44, 5, 96}
fmt.Println(slice)
slice = quicksort(slice)
fmt.Println(slice)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment