Created
November 28, 2017 11:33
-
-
Save jleonardolemos/34c1f6ca964d84604836d2cb8b1d7db2 to your computer and use it in GitHub Desktop.
quicksort recursive script
This file contains hidden or 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" | |
import "os" | |
import "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 número 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 []int, 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