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
Selected Reading
Alternative sorting of an array in JavaScript
We need to write a JavaScript function that sorts an array in an alternating pattern where elements follow the sequence: smaller, larger, smaller, larger, and so on.
The pattern we want to achieve is:
arr[0] < arr[1] > arr[2] < arr[3] > arr[4] < arr[5]...
This creates a zigzag or wave-like pattern in the sorted array. There can be multiple valid solutions for any given input array.
Example Input and Output
For an input array:
const arr = [1, 2, 3, 4, 5, 6];
One possible output could be:
[ 3, 6, 2, 5, 1, 4 ]
Algorithm Explanation
The approach works by:
- First sorting the array in ascending order
- Splitting the sorted array into two halves - smaller and larger elements
- Alternately picking elements from the end of each half to create the zigzag pattern
Implementation
const arr = [1, 2, 3, 4, 5, 6];
const alternateSort = (arr = []) => {
// Sort the array in ascending order
arr.sort((a, b) => a - b);
const N = arr.length;
let mid = Math.floor(N/2);
// Adjust mid for odd length arrays
if(N % 2 !== 0){
mid++;
}
// Split into smaller and larger halves
const small = arr.splice(0, mid);
const big = arr.splice(0, arr.length);
// Rebuild array in alternating pattern
for(let i = 0; i < N; i++){
if(i % 2 === 0){
// Even indices get elements from small half (from end)
arr[i] = small.pop();
} else {
// Odd indices get elements from big half (from end)
arr[i] = big.pop();
}
}
};
alternateSort(arr);
console.log(arr);
[ 3, 6, 2, 5, 1, 4 ]
How It Works
- Sort: The array [1, 2, 3, 4, 5, 6] remains sorted
- Split: Small half: [1, 2, 3], Big half: [4, 5, 6]
- Alternate: Take from end of small (3), then big (6), then small (2), and so on
Time and Space Complexity
- Time Complexity: O(n log n) due to sorting
- Space Complexity: O(n) for the temporary arrays
Conclusion
This algorithm creates an alternating pattern by splitting a sorted array into two halves and rebuilding it by alternately picking elements from the end of each half. The result satisfies the zigzag pattern requirement where each element alternates between being smaller and larger than its neighbors.
Advertisements
