Solidity Array Reversal
pragma solidity ^0.8.0; contract ArrayUtils { /** * @dev Reverses an array of unsigned integers in place. * The function modifies the input array directly. * @param arr The array of uint256 to be reversed. */ function reverseArray(uint256[] storage arr) internal { uint256 n = arr...
This Solidity contract includes a function to reverse an array of unsigned integers in place. It efficiently swaps elements from the beginning and end of the array until the middle is reached. This is a fundamental array...
The `reverseArray` function takes a storage array of `uint256` and reverses its elements in place. It iterates from the start of the array up to `n / 2`, where `n` is the length of the array. In each iteration, it swaps the element at index `i` with the element at index `n - 1 - i`. This ensures that elements are correctly mirrored. The loop condition `i < n / 2` correctly handles both even and odd length arrays; for odd length arrays, the middle element remains in its position. An edge case for an empty array (`n == 0`) is handled by returning immediately. The time complexity is O(n/2), which simplifies to O(n), where n is the number of elements in the array, due to the single loop and constant time swap operations. The space complexity is O(1) as it only uses a temporary variable for swapping and modifies the array in place.
Function reverseArray(arr): n = length of arr If n is 0: Return For i from 0 to n / 2 - 1: temp = arr[i] arr[i] = arr[n - 1 - i] arr[n - 1 - i] = temp