algoritmauzmanı
Sign in
TREN
2.1Array Operations
Lesson 2.1.10

Reversing an array

Reversing an array means swapping the first element with the last, the second with the second to last, and so on. You do not need a second array: two indices start at the ends and swap elements until they meet in the middle. This two-index method will come up again in many algorithms.

What you will learn
  • How swapping with two indices works, and why the loop runs while i < j
  • Why the operation takes time and extra space
  • What happens in the middle when the number of elements is odd or even
5 minTime O(n)Memory O(1)C · Java · Python
Know these first:2.1.2 Traversing an array

1Idea

i starts at the first element and j at the last (size - 1). Each round swaps arr[i] and arr[j], then i moves one to the right and j one to the left. The work is done when the two meet in the middle or cross each other.

A swap needs a temporary variable. As soon as you write arr[i] = arr[j], the old value of arr[i] is gone, so you first put it in temp. In Python, the line arr[i], arr[j] = arr[j], arr[i] does this in one go.

If the number of elements is odd, the middle element stays where it is: i and j reach it together and i < j is false. With an even number of elements the loop runs size / 2 rounds. For an empty or one-element array the loop does not run at all.

Creating a new array and copying the elements into it from back to front also reverses the array, but it needs n elements of extra memory. The swap method works in place.

2Step by step

The drawing reverses a six-element array holding 12, 7, 3, 9, 5 and 8. The numbers under the cells are indices.

0123456712739586sizeij
  1. Start. size is 6; the filled cells are 0 to 5.
  2. i = 0, j = size - 1 = 5. Since i < j, the loop starts.
  3. arr[0] and arr[5] are swapped: 12 and 8 trade places.
  4. i becomes 1 and j becomes 4. Still i < j.
  5. 7 and 5 are swapped.
  6. i becomes 2 and j becomes 3. Still i < j.
  7. 3 and 9 are swapped.
  8. i becomes 3 and j becomes 2. i < j no longer holds; the loop ends. Three swaps were made.
  9. Result: 8, 5, 9, 3, 7, 12. The empty cells were not touched.

#define CAPACITY 8 void reverse(int arr[], int size) {    int i = 0, j = size - 1;    while (i < j) {        int temp = arr[i];  // swap the two ends        arr[i] = arr[j];        arr[j] = temp;        i++;        j--;    }}
void reverse(int[] arr, int size) {    int i = 0, j = size - 1;    while (i < j) {        int temp = arr[i];  // swap the two ends        arr[i] = arr[j];        arr[j] = temp;        i++;        j--;    }}
def reverse(arr, size):    i, j = 0, size - 1    while i < j:        arr[i], arr[j] = arr[j], arr[i]  # swap the two ends        i += 1        j -= 1

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

An array of n elements needs n / 2 swaps; each element moves at most once.

Memory
O(1)

Only two indices and one temporary variable are used; the work is done in place.

Reversing a linked list is also O(n) time and O(1) extra space, but there the links are flipped, not the values. A singly linked list cannot step backwards from the end, so swapping from both ends does not work there.

4Common mistake

The most common mistake is running the loop to the end of the array:

for (int i = 0; i < size; i++) {  // should be size / 2    int temp = arr[i];    arr[i] = arr[size - 1 - i];    arr[size - 1 - i] = temp;}

The first half reverses the array correctly. The second half swaps the same pairs again, and every element goes back to where it was. The result is the original array. Either write i < size / 2 or use two indices with the condition i < j.

5Try it

How many swaps does reversing a 7-element array take?

Show the answer

The answer is A. After three swaps i and j meet at the middle element (index 3). The middle element does not move; 7 / 2 = 3 swaps are enough.

What happens if the loop condition is i <= j instead of i < j?

Show the answer

The answer is B. When i == j, the element is swapped with itself and its value does not change. It costs one extra round, but the result is correct. With an even count i and j are never equal.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.