golang切片奇偶元素位置互换
package main
import "fmt"
func moveSlice(s []int) []int {
if len(s) <= 1 {
return s
}
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
if i&1 == 1 {
i++
}
if j&1 == 0 {
j--
}
s[i], s[j] = s[j], s[i]
}
return s
}
func main() {
s := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
fmt.Println("排序后:", moveSlice(s)) // 排序后: [9 1 7 3 5 4 6 2 8 0]
}