Reverse an Array In-Place

Code

#include <stdio.h>
#include <stdint.h>

void reverse_array(int arr[], int n) 
{
    if (n == 0)
    {
        return;
    }

    uint8_t step = n / 2;
    uint8_t index = 0;
    uint8_t last_index = n - 1;

    for ( ; index < step; index++)
    {
        uint8_t cur_last_index = last_index - index;
        int temp = arr[cur_last_index];
        arr[cur_last_index] = arr[index];
        arr[index] = temp;
    }
}

int main() {
    int n;
    scanf("%d", &n);

    int arr[100];
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    reverse_array(arr, n);

    for (int i = 0; i < n; i++) {
        printf("%d", arr[i]);
        if(i < n-1){
        	printf(" ");
        }
    }
    return 0;
}

Solving Approach

This C program reverses the elements of an integer array "in-place," meaning it swaps elements within the original memory space rather than creating a new copy of the array.

How the Logic Works

The core logic relies on a two-pointer approach (or a "head and tail" swap). To reverse an array, the first element is swapped with the last, the second with the second-to-last, and so on, until the middle of the array is reached.

Breakdown of the Code

1. The reverse_array Function

  • Safety Check: if (n == 0) ensures the function exits immediately if the array is empty, preventing errors.

  • The Midpoint (step): The code calculates n / 2. We only need to loop to the halfway point; if we went all the way to n, we would swap everything twice and end up back where we started.

  • The Swap Loop:

    • It uses index starting at 0 (the front).

    • It calculates cur_last_index (the corresponding position at the back).

    • It uses a temp variable to facilitate the swap (standard "cup-swapping" logic).

2. The main Function

  • Input: It first asks for the size of the array n, then reads n integers into an array of size 100.

  • Execution: It calls the reversal function.

  • Output: It prints the reversed array with spaces between numbers, ensuring there isn't a trailing space at the very end.

Key Technical Notes

Feature

Description

In-place Reversal

This is memory efficient because it uses $O(1)$ extra space (just one temp variable).

Data Types

The code uses uint8_t (from stdint.h) for indices. This is very memory-efficient but limits the array size to 255 elements. If n were larger, the loop would fail.

Time Complexity

The algorithm is $O(n/2)$, which simplifies to $O(n)$ linear time.

Potential Improvement

In your current code, uint8_t is used for index and step. If the user enters an n larger than 255 (like 300), these variables will overflow, causing an infinite loop or a crash. For a more robust program, it is better to use int or size_t for indices to match the array's capacity.

Upvote
Downvote
Loading...

Input

5 1 2 3 4 5

Expected Output

5 4 3 2 1