How to reverse an array in Go

Reversing an array is a common operation in programming involving the reversal of the order of elements within an array. This can be useful in scenarios where data needs to be processed in the opposite direction, such as displaying information in reverse order or implementing algorithms that require reverse traversal of data.

We will delve into the process of reversing a list or array using the Go programming language. This essential operation holds value across various contexts where data manipulation requires the inversion of element order within a collection.

Approach

The algorithm employs a two-pointer approach, strategically manipulating elements by swapping them in pairs starting from the array's ends and moving towards the center. This efficient technique minimizes unnecessary operations and ensures a linear time complexity for array reversal.

1 of 8

Code

The code demonstrates how to reverse an array by swapping elements. The primary objective of the code is to reverse the order of elements within a given integer array.

package main
import "fmt"
func reverseArray(arr []int) {
left := 0
right := len(arr) - 1
for left < right {
arr[left], arr[right] = arr[right], arr[left]
left++
right--
}
}
func main() {
array := []int{1, 2, 3, 4, 5}
fmt.Println("Original array:", array)
reverseArray(array)
fmt.Println("Reversed array:", array)
}
  • Lines 5–13: The function reverseArray takes a single argument: a slice of integers named arr.

    • Lines 6–7: Inside the function, two pointers, left and right, are initialized. left points to the first element of the array (index 0), and right points to the last element of the array (index len(arr) - 1).

    • Lines 8–12: The function then enters a loop that continues as long as the left pointer is less than the right pointer. Inside the loop, the values at the left and right indices are swapped.

    • Lines 10–11: After the swap, the left pointer is incremented, and the right pointer is decremented, effectively moving towards the center of the array. The loop continues until the left and right pointers meet in the middle of the array, resulting in a complete reversal.

Time and space complexity

The algorithm's efficiency in terms of time and space is as follows:

Time Complexity: The time complexity of the array reversal algorithm implemented in the given code is O(n/2)O(n/2), where n is the number of elements in the array. The loop iterates only half of the array's length since it swaps elements from both ends toward the center.

Space Complexity: The space complexity of the algorithm is O(1)O(1), constant space. It doesn't require any additional data structures that grow with the input size; the reversal is performed in place using a fixed amount of memory regardless of the array's length.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved