Reverse an Array

Reverse an Array

·

2 min read

Reverse an array is a pretty common operation in daily programming. In JavaScript, we can just use the built-in function to reverse an array in place.

const arr = [1,2,3,4,5];
arr.reverse(); // [5, 4, 3, 2, 1]

Now let's try to write a function to reverse an array manually.

The first method is very intuitive. To reverse an array, we use two pointers, one from the start and the other from the end. For every step, swap the two values and move two each pointer towards each other.

function reverseArr(arr: number[]): void {
    for (let l = 0, r = arr.length - 1; l < r; l++, r--) {
        [arr[l], arr[r]] = [arr[r], arr[l]];
    }
}

We can see that we use the array deconstructing feature to swap two elements, so we don't need a third variable like in traditional swap process.

Actually, because this is a number array, so we can also use the bitwise OR to swap two element more efficiently.

function reverseArr(arr: number[]): void {
    for (let l = 0, r = arr.length - 1; l < r; l++, r--) {
        arr[l] = arr[l] ^ arr[r];
        arr[r] = arr[l] ^ arr[r];
        arr[l] = arr[l] ^ arr[r];
    }
}

The swapping process can be seen as below, just use the classic bitwise OR feature.

a = a ^ b
b = a(a ^ b) ^ b
a = a(a ^ b) ^ b(a ^ b ^ b)

The above method can be seen as an iterative method. we can reverse an array recursively as well.

The idea is, if we want to reverse an array, we can divide the array into two parts and and swap these two parts. For example, if we have [1,2,3,4,5], we can divide it into [1,2,3] and [4,5], then we swap them and get [4,5,1,2,3]. This is the basic step, all other steps is to repeat this step on all sub arrays. For example, divide [1,2,3] into [1,2] and [3], and swap them and get [3,1,2]. Repeat this process and finally, we should reverse the array successfully.

[1,2,3,4,5] 
=> [1,2,3], [4,5]
=> [4,5,1,2,3]

[1,2,3]
=> [1,2], [3]
=> [3,1,2]

[1,2]
=> [1],[2]
=> [2,1]

[4,5]
=> [4],[5]
=> [5,4]

[4,5,1,2,3]
=> [5,4,3,2,1]

Let's see this process in code.

function reverse(arr: number[]): number[] {
    if (arr.length <= 1) return arr;
    const mid = ~~(arr.length / 2);
    // part after mid + part before mid
    return [...reverse(arr.slice(mid)), ...reverse(arr.slice(0, mid))];
}

function reverseArr(arr: number[]): void {
    const copy = reverse(arr);
    copy.forEach((ele, i) => arr[i] = ele);
}