-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquicksort.go
55 lines (42 loc) · 986 Bytes
/
quicksort.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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 número válido! \n", 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
}
// go run quicksort.go 12 32 43 1 5 30 9 83 84 24 56 37 9 65