partition.go 692 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "time"
  6. )
  7. func threeWayParttion(nums []int, target int) {
  8. nextLess, nextScan, nextLarger := 0, 0, len(nums)-1
  9. for nextScan <= nextLarger {
  10. if nums[nextScan] < target {
  11. swap(nums, nextScan, nextLess)
  12. nextScan++
  13. nextLess++
  14. } else if target < nums[nextScan] {
  15. swap(nums, nextScan, nextLarger)
  16. nextLarger--
  17. } else {
  18. nextScan++
  19. }
  20. }
  21. }
  22. func swap(nums []int, i, j int) {
  23. nums[i], nums[j] = nums[j], nums[i]
  24. }
  25. func main() {
  26. var n int
  27. fmt.Scan(&n)
  28. nums := make([]int, n)
  29. rand.Seed(time.Now().Unix())
  30. for i := range nums {
  31. nums[i] = rand.Intn(3) + 1
  32. }
  33. fmt.Println(nums)
  34. threeWayParttion(nums, 2)
  35. fmt.Println(nums)
  36. }