reverse array without using another array

Reverse Array without using another Array

Reversing an array in JavaScript is a common task that we often come across while working with arrays. There are several ways to reverse an array, one of which is by modifying the same array without using another array.

Approach 1: Swapping elements

The first approach involves swapping elements of an array. In order to reverse the array, we need to swap the first and last elements, then the second and second-last elements, and so on until we reach the middle of the array.


function reverseArray(arr) {
  var len = arr.length,
      middle = Math.floor(len / 2),
      temp;

  for (var i = 0; i < middle; i++) {
    temp = arr[i];
    arr[i] = arr[len - 1 - i];
    arr[len - 1 - i] = temp;
  }

  return arr;
}

// Example usage
var arr = [1, 2, 3, 4, 5];
reverseArray(arr); // [5, 4, 3, 2, 1]

Approach 2: Using recursion

The second approach involves using recursion to reverse the array. In this approach, we swap the first and last elements of the array, and then recursively call the same function on the remaining subarray until the entire array is reversed.


function reverseArray(arr, start = 0) {
  var end = arr.length - 1 - start;

  if (start < end) {
    var temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;

    reverseArray(arr, start + 1);
  }

  return arr;
}

// Example usage
var arr = [1, 2, 3, 4, 5];
reverseArray(arr); // [5, 4, 3, 2, 1]

Conclusion

Both approaches provide efficient ways of reversing an array in JavaScript. While the first approach is more straightforward and easier to understand, the second approach is more elegant and involves less code. Ultimately, it comes down to the programmer's preference and the specific use case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe