Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Large to Small Sorting Algorithm of already sorted array in JavaScript
Suppose we have an array of integers that is already sorted in the increasing order. We are required to write a JavaScript function that without using the inbuilt Array.prototype.sort() method sorts the array like the following ?
-
First number should be the maximum
-
Second number should be the minimum
-
Third number should be the 2nd maximum
-
Fourth number should be the 2nd minimum
-
And so on.
For example ?
If the input array is ?
const arr = [1, 2, 3, 4, 5, 6];
Then the output should be ?
[ 6, 1, 5, 2, 4, 3 ]
How It Works
The algorithm uses two pointers - one at the beginning (left) and one at the end (right) of the sorted array. It alternately picks elements from the right (maximum) and left (minimum) positions, moving the pointers inward after each selection.
Example
Following is the code ?
const arr = [1, 2, 3, 4, 5, 6];
const alternativeSort = (arr = []) => {
const res = [];
let left = 0;
let right = arr.length - 1;
while (res.length < arr.length) {
res.push(arr[right]);
if (left !== right) {
res.push(arr[left]);
}
left++;
right--;
}
return res;
};
console.log(alternativeSort(arr));
Output
[ 6, 1, 5, 2, 4, 3 ]
Step-by-Step Breakdown
Let's trace through the algorithm with the array [1, 2, 3, 4, 5, 6]:
const arr = [1, 2, 3, 4, 5, 6];
const res = [];
let left = 0, right = 5;
// Step 1: Pick arr[5] = 6, then arr[0] = 1
console.log("Step 1:", "right =", arr[right], "left =", arr[left]);
// Step 2: Pick arr[4] = 5, then arr[1] = 2
left = 1; right = 4;
console.log("Step 2:", "right =", arr[right], "left =", arr[left]);
// Step 3: Pick arr[3] = 4, then arr[2] = 3
left = 2; right = 3;
console.log("Step 3:", "right =", arr[right], "left =", arr[left]);
console.log("Final result: [6, 1, 5, 2, 4, 3]");
Step 1: right = 6 left = 1 Step 2: right = 5 left = 2 Step 3: right = 4 left = 3 Final result: [6, 1, 5, 2, 4, 3]
Key Points
Time Complexity: O(n) - single pass through the array
Space Complexity: O(n) - for the result array
Works only with pre-sorted arrays
No built-in sorting method required
Conclusion
This alternative sorting technique efficiently rearranges a sorted array by alternating between maximum and minimum elements using two pointers. It's particularly useful when you need a specific alternating pattern from sorted data.
