Open In App

JavaScript Program to Rearrange Array Alternately

Last Updated : 06 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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}

Approach 1: Iterative Flag-Based

In this approach, The arrayAlternately function rearranges elements of an array alternately, starting with the last element followed by the first, in a concise manner using a loop and a flag to toggle between elements.

Example: In this example, we have function arrayAlternately that takes an array as input and returns a new array containing elements from the input array alternately, starting from both ends and moving towards the center. It iterates through the input array, pushing elements from the right end and left end alternatively into the result array until the left and right indices meet.

Javascript




function arrayAlternately(arr) {
    let result = [];
    let n = arr.length;
  
    for (let left = 0,
        right = n - 1,
        flag = true;
        left <= right;
        flag = !flag) {
        flag ? result.push(arr[right--])
            : result.push(arr[left++]);
    }
  
    return result;
}
  
let input1 = [1, 2, 3, 4, 5, 6, 7];
let resultArray = arrayAlternately(input1);
console.log(resultArray);


Output

[
  7, 1, 6, 2,
  5, 3, 4
]

Time Complexity: O(n)

Space Complexity: O(1)

Approach 2: Using Copy of Array

In this approach, we creates a sorted copy of the input array using slice() and sort(). Then, it iterates through the original array, alternately appending elements from the sorted copy either from the end or the beginning, based on the iteration count.

Example: In this example, we are sorting the elements of ‘inputArray' in a zigzag pattern, where it alternate between taking elements from the beginning and end of a sorted copy of the array ‘tempArray'. The sorted result is stored in the result array, which you print to the console at the end.

Javascript




let inputArray = [12, 15, 67, 81, 90, 92];
let tempArray = 
    inputArray.slice().sort((a, b) => a - b);
let result = [];
let count = 0;
  
for (const num of inputArray) {
    result.push(count % 2 === 0 
        ? tempArray.pop() : tempArray.shift());
    count++;
}
  
console.log(result);


Output

[ 92, 12, 90, 15, 81, 67 ]

Time Complexity: O(n * log(n))

Space Complexity: O(n)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads