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:

  1. First sorting the array in ascending order
  2. Splitting the sorted array into two halves - smaller and larger elements
  3. Alternately picking elements from the end of each half to create the zigzag pattern
Alternative Sorting Process 1. Original: 1 2 3 4 5 6 2. Split: Small half 1 2 3 Big half 4 5 6 3. Result: 3 6 2 5 1 4 < > < > < Pattern: 3 < 6 > 2 < 5 > 1 < 4 Small half elements Big half elements

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

  1. Sort: The array [1, 2, 3, 4, 5, 6] remains sorted
  2. Split: Small half: [1, 2, 3], Big half: [4, 5, 6]
  3. 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.

Updated on: 2026-03-15T23:19:00+05:30

652 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements