go reverse array
package main
import (
"fmt"
)
func reverseArray(arr []int) []int {
left := 0
right := len(arr) - 1
for left < right {
arr[left], arr[right] = arr[right], arr[left]
left++
right--
}
return arr
}
func main() {
arr := []int{1, 2, 3, 4, 5}
reversedArr := reverseArray(arr)
fmt.Println(reversedArr)
}
This Go code defines a function reverseArray
that takes an array of integers as input and returns the array in reverse order. It uses two pointers, left
and right
, starting from opposite ends of the array. It iterates through the array, swapping elements at left
and right
indices until they meet at the middle of the array. The main
function demonstrates the usage by initializing an array, reversing it using the reverseArray
function, and then printing the reversed array.