Implement function reverse that takes a slice of integers and reverses the slice in place without using a temporary slice.
Solution
package main
import "fmt"
func reverse(sw []int) {
for a, b := 0, len(sw)-1; a < b; a, b = a+1, b-1 {
sw[a], sw[b] = sw[b], sw[a]
}
}
Run
Our for loop swaps the values of each element in the slice will slide from left to right. Eventually, all elements will be reversed.