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
Rearrange an array in maximum minimum form by JavaScript
We are required to write a function, say minMax() that takes in an array of Numbers and rearranges the elements such that the greatest element appears first followed by the smallest elements then the second greatest element followed by second smallest element and so on.
For example ?
// if the input array is: const input = [1, 2, 3, 4, 5, 6, 7] // then the output should be: const output = [7, 1, 6, 2, 5, 3, 4]
So, let's write the complete code for this function ?
Approach: Using Two Pointers
The algorithm works by first sorting the array, then using two pointers (left and right) to alternately pick maximum and minimum elements:
const input = [1, 2, 3, 4, 5, 6, 7];
const minMax = arr => {
const array = arr.slice();
array.sort((a, b) => a - b);
for(let start = 0; start
[
7, 1, 6, 2,
5, 3, 4
]
Alternative Approach: Using Two Pointers Directly
Here's a cleaner approach that doesn't use splice operations:
const minMaxAlternate = arr => {
const sorted = [...arr].sort((a, b) => a - b);
const result = [];
let left = 0;
let right = sorted.length - 1;
let isMax = true;
while (left
[
7, 1, 6, 2,
5, 3, 4
]
[ 9, 1, 8, 3, 6, 4 ]
How It Works
The algorithm follows these steps:
- Sort the input array in ascending order
- Use two pointers: left (starts at 0) and right (starts at array.length - 1)
- Alternately pick elements from right (maximum) and left (minimum)
- Move pointers inward after each selection
- Continue until all elements are processed
Comparison
| Approach | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Using splice() | O(n²) | O(n) | Moderate |
| Two Pointers | O(n log n) | O(n) | High |
Conclusion
The two-pointer approach is more efficient and readable for rearranging arrays in maximum-minimum form. It avoids costly splice operations and provides cleaner logic for alternating between maximum and minimum elements.
