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:

  1. Sort the input array in ascending order
  2. Use two pointers: left (starts at 0) and right (starts at array.length - 1)
  3. Alternately pick elements from right (maximum) and left (minimum)
  4. Move pointers inward after each selection
  5. 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.

Updated on: 2026-03-15T23:18:59+05:30

313 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements