Move Zeroes To The Back In Place

Compact non-zero values to the front with two indexes that swap in place, pushing every zero to the back while preserving the relative order of values.

GoData Integrity

Code

gosnippet
25 lines
package main

import "fmt"

// move zeroes to the back in place: slow pins the next non-zero slot
func moveZeroes(nums []int) []int {
	slow := 0
	for fast, v := range nums {
		if v != 0 {
			nums[slow], nums[fast] = nums[fast], nums[slow]
			slow++
		}
	}
	return nums
}

func main() {
	values := []int{0, 1, 0, 3, 12}
	moveZeroes(values)
	fmt.Println(values)
	// 没有零值时交换退化为自交换,原顺序保持不变
	all := []int{5, 6, 7}
	moveZeroes(all)
	fmt.Println(all)
}

Move Zeroes To The Back In Place: reading the source

Everything you would edit lives in moveZeroes and main; the rest is wiring.

The file repeats itself only inside for fast, v := range nums.

Watch out for

  • Imports go no further than the standard library’s fmt — no third-party dependency list to manage.

Applying it

The callable surface: func moveZeroes(nums []int) []int

The entry point wires moveZeroes together — run it once and the whole demo flows.

Statements that matter

func moveZeroes(nums []int) []int {
	slow := 0
	for fast, v := range nums {
		if v != 0 {
			nums[slow], nums[fast] = nums[fast], nums[slow]
			slow++
		}
	}
	return nums
}
func main() {
	values := []int{0, 1, 0, 3, 12}
	moveZeroes(values)
	fmt.Println(values)
	// 没有零值时交换退化为自交换,原顺序保持不变
	all := []int{5, 6, 7}
	moveZeroes(all)
	fmt.Println(all)
}

Interactive Tools for This Topic

FAQ

How do you run Move Zeroes To The Back In Place?
Just run the file; everything it needs ships with the runtime itself.