Skip to content

Instantly share code, notes, and snippets.

@Horaddrim
Last active August 17, 2017 20:29
Show Gist options
  • Save Horaddrim/cc5dd03d323fcb378c8b90bc411a2a85 to your computer and use it in GitHub Desktop.
Save Horaddrim/cc5dd03d323fcb378c8b90bc411a2a85 to your computer and use it in GitHub Desktop.
A simple quicksort algorithm implementation :D And just for doc, I'm loving Golang! It's amazing!!! :D
package main
import (
"fmt"
"os"
"strconv"
)
func main(){
entrada := os.Args[1:]
numeros := make([]int, len(entrada))
for i,n := range entrada{
numero, err := strconv.Atoi(n)
if err != nil {
fmt.Printf("%s não é um numero válido! ",n)
os.Exit(1)
}
numeros[i] = numero
}
fmt.Println(quicksort(numeros))
}
func quicksort(numeros []int) []int{
if len(numeros) <= 1{
return numeros
}
n := make([]int, len(numeros))
copy(n, numeros)
indicePivo := len(n) / 2
pivo := n[indicePivo]
n = append(n[:indicePivo],n[indicePivo + 1:]...)
menores, maiores := particionar(n, pivo)
return append(append(quicksort(menores),pivo),
quicksort(maiores)...)
}
func particionar(numeros []int, pivo int)(menores, maiores []int){
for _,n := range numeros{
if n <= pivo{
menores = append(menores, n)
} else {
maiores = append(maiores, n)
}
}
return menores, maiores
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment