public
Created

Even-Odd Partition in Go

  • Download Gist
even_first.go
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
package main
 
import "fmt"
import "math/rand"
import "time"
 
func main() {
rand.Seed(time.Now().UnixNano())
vals := rand.Perm(10)
fmt.Println(vals)
makeEvenFirst(vals)
fmt.Println(vals)
}
 
func makeEvenFirst(vals []int) {
back := nextBack(len(vals)-1, vals)
for i := 0; i < back; i++ {
v := vals[i]
fmt.Println(v)
if v%2 != 0 {
fmt.Printf("swapping %d and %d\n", v, vals[back])
vals[i] = vals[back]
vals[back] = v
back = nextBack(back-1, vals)
}
}
}
 
func nextBack(back int, vals []int) int {
for back > 0 {
if vals[back]%2 != 0 {
back--
} else {
break
}
}
return back
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.