Reverse Array - C++ Solution

1. Introduction

This blog post discusses a basic yet essential problem in array manipulation: reversing an integer array in-place. This problem is fundamental in understanding array indexing and the concept of in-place operations in C++.

Problem

Given an integer array, the task is to reverse it in-place, without using any built-in functions.

Example:

Input: [1, 2, 3, 4, 5]

Output: [5, 4, 3, 2, 1]

2. Solution Steps

1. Initialize two pointers: one at the start of the array and the other at the end.

2. Swap the elements at these two pointers.

3. Move the start pointer forward and the end pointer backward.

4. Repeat steps 2 and 3 until the start pointer is greater than or equal to the end pointer.

3. Code Program

#include <iostream>
#include <vector>
using namespace std;

// Function to reverse the array
void reverseArray(vector<int>& nums) {
    int start = 0, end = nums.size() - 1;

    while (start < end) {
        // Swap the elements at start and end
        int temp = nums[start];
        nums[start] = nums[end];
        nums[end] = temp;

        // Move the pointers
        start++;
        end--;
    }
}

int main() {
    vector<int> nums = {1, 2, 3, 4, 5};
    reverseArray(nums);

    for (int num : nums) {
        cout << num << " ";
    }
    return 0;
}

Output:

5 4 3 2 1

Explanation:

The reverseArray function uses two pointers to reverse the array in-place. It iterates over the array, swapping the elements at the start and end pointers, then moves the pointers towards each other. This process continues until the pointers meet or cross each other, resulting in a reversed array. The approach is efficient and does not require any additional space, as demonstrated by the output for the given example.


Comments