Skip to content

Instantly share code, notes, and snippets.

@fangdingjun
Last active October 14, 2015 03:13
Show Gist options
  • Save fangdingjun/7c8285b176503acb0a9d to your computer and use it in GitHub Desktop.
Save fangdingjun/7c8285b176503acb0a9d to your computer and use it in GitHub Desktop.
This code implement the Dutch Nation Flag problem, use three-way partition algorithms
package main
import (
"fmt"
)
var flags = []int{1,2,3,3,2,1,1,2,3}
func main() {
var i, j, n int
var low = 1
var high = 3
i, j = 0, 0
n = len(flags) - 1
fmt.Printf("%#v\n", flags)
for flags[j] == low {
i++
j++
}
for flags[n] == high {
n--
}
//fmt.Printf("i=%d, j=%d, n=%d\n", i, j, n)
for j <= n {
switch flags[j] {
case low:
if i == j {
j++
continue
}
swap(i, j)
i++
case high:
swap(n, j)
n--
default:
j++
}
//fmt.Printf("i=%d, j=%d, n=%d\n", i, j, n)
}
fmt.Printf("%#v\n", flags)
}
func swap(x, y int) {
//fmt.Printf("flags[%d]: %d <->flags[%d]: %d\n", x, flags[x], y, flags[y])
flags[x], flags[y] = flags[y], flags[x]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment