Two-Pointer Approach
In this approach, we use two pointers, one starting from the beginning (left) and one starting from the end (right) of the array. We alternately pick elements from the end and the beginning and place them in the result array until we traverse the entire array.
Example: This function takes an input array, uses two pointers to pick elements alternately from the end and the beginning, and stores them in the result array. It then prints the rearranged array.
function rearrangeAlternately(arr) {
let n = arr.length;
let result = new Array(n);
let left = 0, right = n - 1;
let index = 0;
while (left <= right) {
if (index % 2 === 0) {
result[index++] = arr[right--];
} else {
result[index++] = arr[left++];
}
}
return result;
}
let inputArray1 = [1, 2, 3, 4, 5, 6, 7];
let rearrangedArray1 = rearrangeAlternately(inputArray1);
console.log(rearrangedArray1);
let inputArray2 = [12, 15, 67, 81, 90, 92];
let rearrangedArray2 = rearrangeAlternately(inputArray2);
console.log(rearrangedArray2);
Output
[ 7, 1, 6, 2, 5, 3, 4 ] [ 92, 12, 90, 15, 81, 67 ]
Time Complexity: O(n)
Space Complexity: O(n)
JavaScript Program to Rearrange Array Alternately
Rearranging an array alternately means, If we have a sorted array then we have to rearrange the array such that the first largest element should come at index-0(0-based indexing), first smallest element should come at index-1, similarly, second largest element should come at index-3 and second smallest element should come at index-4 and so on. Below are the examples:
Example:
Input: arr1 = {1, 2, 3, 4, 5, 6, 7}
Output: {7, 1, 6, 2, 5, 3, 4}
Input: arr2 = {12, 15, 67, 81, 90, 92}
Output: {92, 12, 90, 15, 81, 67}