JavaScript Program to Rearrange Array Alternately
Last Updated :
26 Aug, 2024
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}
Here are some common approaches:
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)
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)
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.
JavaScript
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)
In-Place Rearrangement Using Auxiliary Index Array
In this approach, we rearrange the array elements alternately in-place by using an auxiliary array to keep track of the indices for the largest and smallest elements. This way, we avoid the need for additional space to store the result array, thus reducing the space complexity.
Steps:
- Create Auxiliary Index Array:
- Create an auxiliary array to store the indices for the largest and smallest elements.
- Fill Auxiliary Array Alternately:
- Fill the auxiliary array alternately with indices from the end (for largest elements) and the beginning (for smallest elements) of the sorted array.
- Rearrange In-Place:
- Use the auxiliary array to rearrange the elements in the original array in-place.
Example:
JavaScript
function rearrangeAlternately(arr) {
let n = arr.length;
let aux = new Array(n);
// Sort the array to get smallest and largest elements easily
arr.sort((a, b) => a - b);
// Fill aux array with indices
let left = 0, right = n - 1;
for (let i = 0; i < n; i++) {
if (i % 2 === 0) {
aux[i] = arr[right--]; // Largest element
} else {
aux[i] = arr[left++]; // Smallest element
}
}
// Copy the elements from aux array back to the original array
for (let i = 0; i < n; i++) {
arr[i] = aux[i];
}
return arr;
}
// Examples
let arr1 = [1, 2, 3, 4, 5, 6, 7];
console.log(rearrangeAlternately(arr1)); // Output: [7, 1, 6, 2, 5, 3, 4]
let arr2 = [12, 15, 67, 81, 90, 92];
console.log(rearrangeAlternately(arr2)); // Output: [92, 12, 90, 15, 81, 67]
Output[
7, 1, 6, 2,
5, 3, 4
]
[ 92, 12, 90, 15, 81, 67 ]
In-Place Rearrangement Using Index Manipulation
In this approach, we rearrange the array elements alternately in-place by leveraging index manipulation techniques. This method avoids the use of extra space for storing indices or additional arrays, making it an efficient solution.
Example:
JavaScript
function rearrangeArrayInPlace(arr) {
arr.sort((a, b) => a - b);
let n = arr.length;
let mid = Math.floor((n - 1) / 2);
function swap(i, j) {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
for (let i = 1; i <= mid; i += 2) {
swap(i, n - i);
}
return arr;
}
let arr1 = [1, 2, 3, 4, 5, 6, 7];
console.log(rearrangeArrayInPlace(arr1));
let arr2 = [12, 15, 67, 81, 90, 92];
console.log(rearrangeArrayInPlace(arr2));
Output[
1, 7, 3, 5,
4, 6, 2
]
[ 12, 92, 67, 81, 90, 15 ]
In-Place Rearrangement Using Mathematical Encoding
In this method, we encode both the smallest and largest elements into the same array using mathematical tricks to avoid using extra space for another array. We then decode the elements to get the final result.
Steps:
- Encode Elements:
- Use a mathematical formula to store both the smallest and largest elements at the same index.
- Encode the largest element at every even index and the smallest element at every odd index.
- Decode Elements:
- Decode the values from the encoded array to get the original array rearranged as required.
Example:
JavaScript
function rearrangeArrayMathematical(arr) {
let n = arr.length;
if (n <= 1) return arr;
// Step 1: Find the maximum element in the array to use for encoding
let maxElement = arr[n - 1] + 1;
// Step 2: Rearrange the array using encoding and decoding
let left = 0, right = n - 1;
for (let i = 0; i < n; i++) {
if (i % 2 === 0) {
// Store the largest element at even index
arr[i] += (arr[right--] % maxElement) * maxElement;
} else {
// Store the smallest element at odd index
arr[i] += (arr[left++] % maxElement) * maxElement;
}
}
// Step 3: Decode the values to get the rearranged array
for (let i = 0; i < n; i++) {
arr[i] = Math.floor(arr[i] / maxElement);
}
return arr;
}
let arr1 = [1, 2, 3, 4, 5, 6, 7];
console.log(rearrangeArrayMathematical(arr1));
let arr2 = [12, 15, 67, 81, 90, 92];
console.log(rearrangeArrayMathematical(arr2));
Output[
7, 1, 6, 2,
5, 3, 4
]
[ 92, 12, 90, 15, 81, 67 ]
Similar Reads
JavaScript Program to Sort the 2D Array Across Rows
We will see how to sort the 2D Array across rows using a Javascript program. we can sort the 2D Array Across Rows in many ways including Bubble Sort Algorithm, Array.prototype.sort() method, Insertion Sort Algorithm, Using the Selection Sort Algorithm, and Merge Sort Algorithm. Example: Input:[[8 5
6 min read
Alternative Sorting of an Array using JavaScript
Alternative sorting means we have to arrange the elements of an array in such a way that the first element is the first maximum and the second element is the first minimum, the third element is the second maximum, the fourth element is the second minimum, and so on.Example:Input: array = [5, 6, 2, 4
3 min read
JavaScript Program to Reorder an Array According to Given Indexes
Reordering an array according to given indexes means rearranging the elements of an array based on a separate array that specifies the desired order. Each element in the given index array corresponds to the index of the element in the original array at which it should be placed in the reordered arra
3 min read
JavaScript Program to Rearrange Array such that Even Positioned are Greater than Odd
In this article, we will cover rearranging arrays such that even positions are greater than odd in JavaScript. Give there is an array that we need to rearrange in the pattern where the even positioned are greater than the odd positioned in JavaScript. We will see the code for each approach along wit
4 min read
JavaScript Program for Left Rotate by One in an Array
In this article, we are going to learn about left Rotation by One in an Array by using JavaScript, Left rotation by one in an array means shifting all elements from one position to the left, with the last element moving to the first position. The order of elements is cyclically rotated while maintai
5 min read
JavaScript Program for Insertion Sort
What is Insertion Sort Algorithm?Insertion sorting is one of the sorting techniques that is based on iterating the array and finding the right position for every element. It compares the current element to the predecessors, if the element is small compare it with the elements before. Move ahead to a
4 min read
JavaScript Program for Selection Sort
What is Selection Sort in JavaScript?Selection sort is a simple and efficient algorithm that works on selecting either the smallest or the largest element of the list or array and moving it to the correct position. Working of Selection SortConsider the following arrayarr = [ 64, 25, 12, 22, 11]This
3 min read
JavaScript Program for Quick Sort
What is Quick Sort Algorithm?Quick sort is one of the sorting algorithms that works on the idea of divide and conquer. It takes an element as a pivot and partitions the given array around that pivot by placing it in the correct position in the sorted array. The pivot element can be selected in the f
4 min read
JavaScript Program for Merge Sort
What is Merge Sort Algorithm?Merge sort is one of the sorting techniques that work on the divide and conquer approach. The Given array is divided in half again and again and those parts are arranged in sorted order and merged back to form the complete sorted array. Working of Merge SortTo Understand
3 min read
Javascript Program to Interchange elements of first and last rows in matrix
Given a 4 x 4 matrix, we have to interchange the elements of first and last row and show the resulting matrix.Examples : Input : 3 4 5 0 2 6 1 2 2 7 1 2 2 1 1 2Output : 2 1 1 2 2 6 1 2 2 7 1 2 3 4 5 0Input : 9 7 5 1 2 3 4 1 5 6 6 5 1 2 3 1Output : 1 2 3 1 2 3 4 1 5 6 6 5 9 7 5 1The approach is very
2 min read