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 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 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 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 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
JavaScript Program to Find Lexicographically Next Permutation Given an array of distinct integers, we want to find the lexicographically next permutation of those elements. In simple words, when all the possible permutations of an array are placed in a sorted order, it is the lexicographic order of those permutations. In this case, we have to find the next gre
5 min read
Javascript Program to Sort an array in wave form Given an unsorted array of integers, sort the array into a wave like array. An array 'arr[0..n-1]' is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= .....Examples: Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80} Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} OR {
4 min read
Javascript Program For Sorting An Array Of 0s, 1s and 2s Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.Examples:Input: {0, 1, 2, 0, 1, 2}Output: {0, 0, 1, 1, 2, 2}Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}Output: {0, 0, 0, 0, 0
5 min read
Javascript Program to Check if it is possible to sort the array after rotating it Given an array of size N, the task is to determine whether its possible to sort the array or not by just one shuffle. In one shuffle, we can shift some contiguous elements from the end of the array and place it in the front of the array.For eg: A = {2, 3, 1, 2}, we can shift {1, 2} from the end of t
3 min read
JavaScript Progam to rearrange an array in maximum minimum form using Two Pointer Technique In this article, we are going to learn about rearranging an array in maximum minimum form using the Pointer Technique in JavaScript. Rearranging an array in maximum-minimum form with the Two Pointer Technique involves sorting the array, then alternately selecting elements from the smallest and large
4 min read
Javascript Program to Move all zeroes to end of array | Set-2 (Using single traversal) Given an array of n numbers. The problem is to move all the 0's to the end of the array while maintaining the order of the other elements. Only single traversal of the array is required.Examples: Input : arr[] = {1, 2, 0, 0, 0, 3, 6}Output : 1 2 3 6 0 0 0Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0,
2 min read