Alternative Sorting of an Array using JavaScript
Last Updated :
05 Jul, 2024
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, 1]
Output: array = [6, 1, 5, 2, 4, 3]
Explanation:
Sorting the array: [1, 2, 3, 4, 5, 6]
First element (1) from the sorted array.
Last element (6) from the sorted array.
Second element (2) from the sorted array.
Second-to-last element (5) from the sorted array.
Third element (3) from the sorted array.
Third-to-last element (4) from the sorted array
Now reordered the array: [6, 1, 5, 2, 4, 3]
Below are the approaches for Alternative sorting of an array using JavaScript:
Sorting and Rearranging
In this approach, sort an array and then rearranges it in an alternating high-low order in JavaScript. It first sorts the array in ascending order, then uses a while loop to alternately push the largest remaining element and the smallest remaining element to a new array. The final array is returned and logged.
Example: The example below shows Alternative sorting of an array using Sorting and Rearranging.
JavaScript
function alternativeSort(arr) {
arr.sort((a, b) => a - b);
let answer = [];
let start = 0, end = arr.length - 1;
while (start <= end) {
answer.push(arr[end--]);
if (start <= end) {
answer.push(arr[start++]);
}
}
return answer;
}
const arr1 = [5, 6, 2, 4, 3, 1];
console.log("Sorted Array with Alternative Sorting:",
alternativeSort(arr1));
OutputSorted Array with Alternative Sorting: [ 6, 1, 5, 2, 4, 3 ]
Time complexity: O(n log n)
Space complexity: O(n)
Using Two Arrays
Sort the array in ascending order. Divide the sorted array into two halves where maxArray, containing elements from the middle index to the end, reversed and minArray, containing elements from the start to the middle index. Create an empty result array. Iterate over maxArray and minArray alternately, pushing elements into the result array. If one array has fewer elements, handle them appropriately. Return the result array.
Example: The example below shows Alternative sorting of an array using Two Arrays.
JavaScript
function alternativeSort(arr) {
arr.sort((a, b) => a - b);
// Calculate the middle index
const mid = Math.ceil(arr.length / 2);
// Split the array into two halves
const maxArray = arr.slice(mid).reverse();
const minArray = arr.slice(0, mid);
// Interleave the two arrays
const result = [];
for (let i = 0; i < mid; i++) {
result.push(maxArray[i]);
if (minArray[i] !== undefined) {
result.push(minArray[i]);
}
}
return result;
}
const arr = [5, 6, 2, 4, 3, 1];
console.log("Sorted Array with Alternative Sorting:",
alternativeSort(arr));
OutputSorted Array with Alternative Sorting: [ 6, 1, 5, 2, 4, 3 ]
Time complexity: O(n log n).
Space complexity: O(n).
Similar Reads
JavaScript Program to Convert an Array into a String We have been given an array as an input that consists of various elements and our task is to convert this array of elements into a string by using JavaScript. Below we have added the examples for better understanding:Example: Input: arr= [1,2,3,4,5,6]Output: 1,2,3,4,5,6Table of ContentUsing arr.join
4 min read
JavaScript - Length of an Array in JS These are the following approaches to find the length of the given array: 1. Using length Property - Mostly UsedIn this approach, we have used the length property to determine the length of an array.JavaScriptlet a = [12, 4.7, 9, 10] console.log(a.length)Output4 2. Using for of and for in LoopWe hav
1 min read
JavaScript- Delete all Occurrences in a JS Array These are the following ways to remove all Occurrences of an element in a JS Array: 1. Using filter() method( Simple and Easy for Long Arrays)The filter() method creates a new array with all elements that passed the test implemented by the given callback function.JavaScriptfunction fun(a, e) { if (!
2 min read
JavaScript Program to Transform Nested Array into Normal Array JavaScript allows us to convert nested arrays into a single, flat array using JavaScript. By simplifying nested structures, you can enhance the manageability and readability of your code. Example: Input: [[1, 2], [3, [4, 5]]] Output: [1, 2, 3, 4, 5]Below are the approaches to transform nested arrays
3 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 to Split Map Keys and Values into Separate Arrays In this article, we are going to learn about splitting map keys and values into separate arrays by using JavaScript. Splitting map keys and values into separate arrays refers to the process of taking a collection of key-value pairs stored in a map data structure and separating the keys and values in
5 min read
JavaScript - Access Elements in JS Array These are the following ways to Access Elements in an Array:1. Using Square Bracket NotationWe can access elements in an array by using their index, where the index starts from 0 for the first element. We can access using the bracket notation.JavaScriptconst a = [10, 20, 30, 40, 50]; const v = a[3];
2 min read
JavaScript Program to Create an Array with a Specific Length and Pre-filled Values In JavaScript, we can create an array with a specific length and pre-filled values using various approaches. This can be useful when we need to initialize an array with default or placeholder values before populating it with actual data.Table of ContentMethod 1: Using the Array() Constructor and fil
3 min read
Implement Custom Array Flat method in JavaScript The flat() method in JavaScript is used to flatten nested arrays. By using that function we can directly convert any type of array into 1D array. These are the following approaches to implementing a custom array flat method in JavaScript: Table of Content Using Recursion approachUsing Iterative appr
2 min read
JavaScript Array Search And Remove String. Arrays are widely used to store and manipulate collections of data. Sometimes we may need to search for a specific string within an array and remove it. This operation can be useful in various cases, such as filtering out unwanted items, managing user inputs, or processing data from an external sour
2 min read