Reversing an array means rearranging its elements so that the first element becomes the last, the second becomes the second last, and so on.
- Uses two pointers to swap elements from both ends of the array.
- Demonstrates pointer arithmetic instead of array indexing.
Example
Input: arr[] = {10, 20, 30, 40, 50}
Output: 50 40 30 20 10
Working of the Two-Pointer Approach
An array name decays to a pointer to its first element when passed to a function. Therefore, the parameter int* arr receives the address of the first element of the array. This approach uses pointer arithmetic instead of array indexing to reverse the array.
- start points to the first element of the array.
- end points to the last element of the array.
- The values at these pointers are swapped.
- start moves forward while end moves backward until they meet.
- The array is reversed in-place without using an extra array.
Example: Program to Reverse an Array Using Pointers
#include <iostream>
using namespace std;
void reverseArray(int* arr, int size) {
// Pointer to first element
int* start = arr;
// pointer to last element
int* end = arr + size - 1;
// Until both pointers meet
while (start < end) {
// Swap values at start and end
int temp = *start;
*start = *end;
*end = temp;
// Move pointers
start++;
end--;
}
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
reverseArray(arr, size);
for (int i = 0; i < size; i++)
cout << *(arr + i) << " ";
cout << endl;
return 0;
}
Output
50 40 30 20 10
Explanation
- The function parameter int* arr receives the address of the first element of the array.
- start is initialized to the beginning of the array, while end points to the last element.
- The values at start and end are swapped using a temporary variable.
- After each swap, start moves forward and end moves backward.
- The process continues until both pointers meet or cross each other, leaving the array reversed.
This method modifies the original array directly without creating an additional array, making it both time and space efficient.
Time Complexity: O(n)
Auxiliary Space: O(1)