Created
August 22, 2017 14:14
-
-
Save Horaddrim/1067e39a92b5a30dd48e60b5d6f6713c to your computer and use it in GitHub Desktop.
A simple demonstration of the power of channels, and a play with the quicksort algorithm
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" | |
) | |
func separar(nums []int, i, p chan<- int, pronto chan<- bool) { | |
for _, n := range nums { | |
if n%2 == 0 { | |
p <- n | |
} else { | |
i <- n | |
} | |
} | |
pronto <- true | |
} | |
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 | |
} | |
func main() { | |
i, p := make(chan int), make(chan int) | |
pronto := make(chan bool) | |
nums := []int{1, 23, 46, 5, 8, 6, 7, 4, 99, 100} | |
go separar(nums, i, p, pronto) | |
var pares, impares []int | |
fim := false | |
for !fim { | |
select { | |
case n := <-i: | |
impares = append(impares, n) | |
fmt.Printf("Ímpares: %v\n", impares) | |
case n := <-p: | |
pares = append(pares, n) | |
fmt.Printf("Pares: %v\n", pares) | |
case fim = <-pronto: | |
fmt.Println("Fim") | |
fmt.Printf("Ímpares: %v / Pares: %v \n", impares, pares) | |
} | |
} | |
fmt.Printf("Números organizados! : \n") | |
fmt.Printf("Pares: %v\n", quicksort(pares)) | |
fmt.Printf("Ímpares: %v\n", quicksort(impares)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment