Alternative shuffle in JavaScript

An alternatively shuffled array in JavaScript is an array of numbers where elements are arranged such that the greatest number is followed by the smallest element, second greatest element is followed by second smallest element, and so on.

For example, if we have an input array:

[11, 7, 9, 3, 5, 1, 13]

The alternatively shuffled output should be:

[13, 1, 11, 3, 9, 5, 7]

How Alternative Shuffling Works

The algorithm follows these steps:

  • Sort the array in ascending order
  • Take the largest element from the end and place it at even positions
  • Take the smallest element from the beginning and place it at odd positions

Implementation

const arr = [11, 7, 9, 3, 5, 1, 13];

const alternateShuffle = (arr) => {
    const sorted = arr.slice().sort((a, b) => a - b);
    const result = [];
    let left = 0;
    let right = sorted.length - 1;
    
    for (let i = 0; i 

Original array: [ 11, 7, 9, 3, 5, 1, 13 ]
Alternative shuffle: [ 13, 1, 11, 3, 9, 5, 7 ]

Step-by-Step Example

Let's trace through the algorithm:

const arr = [11, 7, 9, 3, 5, 1, 13];

const alternateShuffle = (arr) => {
    const sorted = arr.slice().sort((a, b) => a - b);
    console.log("Sorted array:", sorted);
    
    const result = [];
    let left = 0;
    let right = sorted.length - 1;
    
    for (let i = 0; i 

Sorted array: [ 1, 3, 5, 7, 9, 11, 13 ]
Step 1: Added 13 from right (largest)
Step 2: Added 1 from left (smallest)
Step 3: Added 11 from right (largest)
Step 4: Added 3 from left (smallest)
Step 5: Added 9 from right (largest)
Step 6: Added 5 from left (smallest)
Step 7: Added 7 from right (largest)
Result: [ 13, 1, 11, 3, 9, 5, 7 ]

Alternative Implementation Using Two Pointers

const alternateShuffle2 = (arr) => {
    const sorted = arr.slice().sort((a, b) => a - b);
    const result = new Array(sorted.length);
    let left = 0, right = sorted.length - 1;
    
    for (let i = 0; i 

Original: [ 5, 2, 8, 1, 9 ]
Alternative shuffle: [ 9, 1, 8, 2, 5 ]

Conclusion

Alternative shuffling creates a pattern where large and small elements alternate in the array. This technique is useful in scenarios where you need to distribute values evenly or create balanced arrangements.

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

389 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements