Reverse an array in C

Reverse an array in C
Posted on 27-08-2023

Reverse an array in C

Code:

#include <stdio.h>

void reverseArray(int arr[], int size) {
int left = 0;
int right = size - 1;

while (left < right) {
// Swap the elements at positions left and right
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;

// Move the pointers towards the center
left++;
right--;
}
}

int main() {
int originalArray[] = {1, 2, 3, 4, 5};
int size = sizeof(originalArray) / sizeof(originalArray[0]);

printf("Original array: ");
for (int i = 0; i < size; i++) {
printf("%d ", originalArray[i]);
}
printf("\n");

reverseArray(originalArray, size);

printf("Reversed array: ");
for (int i = 0; i < size; i++) {
printf("%d ", originalArray[i]);
}
printf("\n");

return 0;
}

When you run this C program, it will output:

Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1

 

Explanation:

#include <stdio.h>

This line includes the standard input-output library. It's needed to use functions like printf and scanf.

void reverseArray(int arr[], int size) {

This line starts the definition of a function named reverseArray. The function takes two parameters: an array arr and an integer size. This function will be responsible for reversing the array.

int left = 0;
int right = size - 1;

Here, we're declaring two variables left and right which will act as pointers to the leftmost and rightmost elements of the array, respectively. left points to the first element (index 0), and right points to the last element (index size - 1).

while (left < right) {

This is the start of a loop. As long as left is less than right, the loop will continue. This ensures that we only swap elements until we reach the middle of the array.

int temp = arr[left];

Here, we're creating a temporary variable temp to store the value of the element at the left position. This is because we're going to swap elements, and we need to temporarily store one of them.

arr[left] = arr[right];
arr[right] = temp;

These lines perform the actual swapping of elements. We're assigning the value of the element at the right position to the element at the left position, and then assigning the value of the temporary variable (temp) to the element at the right position.

left++;
right--;

These lines move the pointers left and right towards the center of the array. left is incremented (moved to the right), and right is decremented (moved to the left).

}

This curly brace marks the end of the while loop. The loop continues until all the necessary swaps have been done to reverse the array.

}

This curly brace marks the end of the reverseArray function.

int main() {

This is the beginning of the main function, which is the entry point of the program.

int originalArray[] = {1, 2, 3, 4, 5};
int size = sizeof(originalArray) / sizeof(originalArray[0]);

Here, we're creating an array called originalArray with some initial values. The size variable is calculated as the total number of bytes occupied by the array divided by the size of a single element in the array.

printf("Original array: ");
for (int i = 0; i < size; i++) {
printf("%d ", originalArray[i]);
}
printf("\n");

This loop iterates through the originalArray and prints each element followed by a space. After printing all elements, a newline character is printed to start a new line.

reverseArray(originalArray, size);

This line calls the reverseArray function, passing the originalArray and size as arguments to reverse the array.

printf("Reversed array: ");
for (int i = 0; i < size; i++) {
printf("%d ", originalArray[i]);
}
printf("\n");

Similarly to before, this loop iterates through the now reversed originalArray and prints each element followed by a space. After printing all reversed elements, a newline character is printed.

return 0;
}

This line signals that the main function has completed successfully and returns the value 0, indicating the program's success to the operating system.

Algorithm:

Algorithm for Reversing an Array:

  1. Input:

    • arr[]: An array of integers.

    • size: The number of elements in the array.

  2. Procedure: reverseArray Function

    • Initialize two pointers: left pointing to the first element of the array (0) and right pointing to the last element of the array (size - 1).

    • While left is less than right:

      • Swap the elements at positions arr[left] and arr[right] using a temporary variable temp.

      • Increment left and decrement right to move the pointers towards the center of the array.

    • End of loop.

  3. Output:

    • The array arr will be reversed in place.

  4. Main Program (main function):

    • Initialize an array originalArray with given values.

    • Calculate the size of the array using sizeof(originalArray) / sizeof(originalArray[0]).

    • Print the original array elements using a for loop.

    • Call the reverseArray function to reverse the originalArray.

    • Print the reversed array elements using another for loop.

Pseudocode:

reverseArray(arr[], size):
left = 0
right = size - 1

while left < right:
temp = arr[left]
arr[left] = arr[right]
arr[right] = temp
left = left + 1
right = right - 1

main():
originalArray[] = {1, 2, 3, 4, 5}
size = length of originalArray

print "Original array:"
for i = 0 to size - 1:
print originalArray[i]

reverseArray(originalArray, size)

print "Reversed array:"
for i = 0 to size - 1:
print originalArray[i]

This pseudocode outlines the step-by-step process of reversing an array using the provided code. The reverseArray function swaps elements using pointers to achieve the reversal in-place. The main program initializes the array, prints the original and reversed arrays, and demonstrates the functionality of the code.

Time Complexity:

The time complexity of the program can be analyzed based on the reverseArray function, which is responsible for the primary work of reversing the array. The time complexity of the entire program is driven by the complexity of this function.

The reverseArray function uses a two-pointer approach to swap elements and reverse the array. Since each pair of elements is swapped only once, the number of swaps needed is roughly half of the total number of elements in the array.

Therefore, the time complexity of the reverseArray function is O(n/2), where n is the number of elements in the array.

However, in big O notation, we typically drop the constant factors, so the time complexity can be simplified to O(n).

The main function performs additional operations, such as printing the arrays, but these operations are linear in nature and do not significantly contribute to the overall time complexity. Therefore, the dominant factor is the time complexity of the reverseArray function, which is O(n).

Space Complexity:

The space complexity of the program is O(1), which means it uses a constant amount of extra space regardless of the input size.

Here's why:

  1. The program uses a fixed amount of memory for variables (left, right, temp, originalArray, size, i). These variables do not scale with the input size and occupy a constant amount of memory throughout the program's execution.

  2. The reverseArray function operates directly on the input array without creating any additional data structures that would grow with the input size. The swapping of elements occurs in-place, meaning that no additional memory is required.

  3. The memory usage does not increase as the size of the array increases. Regardless of the number of elements in the array, the memory requirements remain constant.

Since the memory used by the program doesn't grow with the input size and is constant, the space complexity is O(1).

Thank You