This is the approach many beginners (myself included) think of first:
“Why not create a new array and fill it in reverse order?”
#include <iostream>
#include <vector>
using namespace std;
void reverseArray(vector<int> &arr) {
int n = arr.size();
vector<int> temp(n);
for (int i = 0; i < n; i++)
temp[i] = arr[n - i - 1];
for (int i = 0; i < n; i++)
arr[i] = temp[i];
}
int main() {
vector<int> arr = {1, 4, 3, 2, 6, 5};
reverseArray(arr);
for (int val : arr)
cout << val << " ";
}
🔍 Analysis
✅ Simple and readable
❌ Not memory-efficient – It uses an extra array of the same size (O(n) space)
✅ Optimal Approach: In-Place Reversal Using Swapping
Then I explored another way—swapping elements from both ends of the array until the middle is reached.
void reverseArray(vector<int>& arr) {
int left = 0, right = arr.size() - 1;
while (left < right) {
swap(arr[left], arr[right]);
left++;
right--;
}
}
Or Using a For Loop:
void reverseArray(vector<int>& arr) {
for (int i = 0; i < arr.size() / 2; i++) {
swap(arr[i], arr[arr.size() - 1 - i]);
}
}
🔍 Analysis
✅ Efficient – Reverses the array in O(n) time and O(1) space
✅ Professional standard – Used in interviews and real-world problems
✅ Doesn't require extra memory
Top comments (0)