Sorting odd and even elements separately JavaScript

In JavaScript, we can sort odd and even positioned elements separately within an array while maintaining their relative positions. This approach sorts elements at even indices (0, 2, 4...) and odd indices (1, 3, 5...) independently.

Understanding the Problem

Given an array, we need to sort elements at even indices separately from elements at odd indices. For example, with array [9, 2, 7, 4, 5, 6, 3, 8, 1]:

  • Even indices (0, 2, 4, 6, 8): [9, 7, 5, 3, 1] ? sorted: [1, 3, 5, 7, 9]
  • Odd indices (1, 3, 5, 7): [2, 4, 6, 8] ? sorted: [2, 4, 6, 8]

Algorithm Steps

Step 1 ? Create a function that accepts an array parameter.

Step 2 ? Use bubble sort to sort even-indexed and odd-indexed elements separately.

Step 3 ? Loop through the array with a swapped flag set to false initially.

Step 4 ? Compare adjacent even-indexed elements and swap if needed.

Step 5 ? Compare adjacent odd-indexed elements and swap if needed.

Step 6 ? Repeat until no swaps are needed.

Implementation

// Function to sort odd and even indexed elements separately
function sortOddEven(arr) {
    const n = arr.length;
    let swapped;
    
    do {
        swapped = false;
        
        // Sort even indexed elements (0, 2, 4, ...)
        for (let i = 0; i < n - 2; i += 2) {
            if (arr[i] > arr[i + 2]) {
                [arr[i], arr[i + 2]] = [arr[i + 2], arr[i]];
                swapped = true;
            }
        }
        
        // Sort odd indexed elements (1, 3, 5, ...)
        for (let i = 1; i < n - 2; i += 2) {
            if (arr[i] > arr[i + 2]) {
                [arr[i], arr[i + 2]] = [arr[i + 2], arr[i]];
                swapped = true;
            }
        }
    } while (swapped);
    
    return arr;
}

// Test the function
const originalArray = [9, 2, 7, 4, 5, 6, 3, 8, 1];
console.log("Original array:", originalArray);

const sortedArray = sortOddEven([...originalArray]); // Use spread to avoid mutating original
console.log("After sorting odd/even separately:", sortedArray);
Original array: [9, 2, 7, 4, 5, 6, 3, 8, 1]
After sorting odd/even separately: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Step-by-Step Visualization

function sortOddEvenWithSteps(arr) {
    const n = arr.length;
    let swapped;
    let step = 1;
    
    console.log("Initial array:", arr);
    console.log("Even positions (0,2,4...):", arr.filter((_, i) => i % 2 === 0));
    console.log("Odd positions (1,3,5...):", arr.filter((_, i) => i % 2 === 1));
    console.log("---");
    
    do {
        swapped = false;
        
        // Sort even indexed elements
        for (let i = 0; i < n - 2; i += 2) {
            if (arr[i] > arr[i + 2]) {
                console.log(`Step ${step}: Swapping even elements ${arr[i]} and ${arr[i + 2]} at positions ${i} and ${i + 2}`);
                [arr[i], arr[i + 2]] = [arr[i + 2], arr[i]];
                swapped = true;
                step++;
            }
        }
        
        // Sort odd indexed elements
        for (let i = 1; i < n - 2; i += 2) {
            if (arr[i] > arr[i + 2]) {
                console.log(`Step ${step}: Swapping odd elements ${arr[i]} and ${arr[i + 2]} at positions ${i} and ${i + 2}`);
                [arr[i], arr[i + 2]] = [arr[i + 2], arr[i]];
                swapped = true;
                step++;
            }
        }
    } while (swapped);
    
    console.log("Final sorted array:", arr);
    return arr;
}

sortOddEvenWithSteps([9, 2, 7, 4, 5, 6, 3, 8, 1]);
Initial array: [9, 2, 7, 4, 5, 6, 3, 8, 1]
Even positions (0,2,4...): [9, 7, 5, 3, 1]
Odd positions (1,3,5...): [2, 4, 6, 8]
---
Step 1: Swapping even elements 9 and 7 at positions 0 and 2
Step 2: Swapping even elements 9 and 5 at positions 2 and 4
Step 3: Swapping even elements 9 and 3 at positions 4 and 6
Step 4: Swapping even elements 9 and 1 at positions 6 and 8
Step 5: Swapping even elements 7 and 5 at positions 0 and 2
Step 6: Swapping even elements 7 and 3 at positions 2 and 4
Step 7: Swapping even elements 7 and 1 at positions 4 and 6
Step 8: Swapping even elements 5 and 3 at positions 0 and 2
Step 9: Swapping even elements 5 and 1 at positions 2 and 4
Step 10: Swapping even elements 3 and 1 at positions 0 and 2
Final sorted array: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Alternative Approach Using Built-in Sort

function sortOddEvenBuiltIn(arr) {
    const evenElements = [];
    const oddElements = [];
    
    // Separate elements by index position
    for (let i = 0; i < arr.length; i++) {
        if (i % 2 === 0) {
            evenElements.push(arr[i]);
        } else {
            oddElements.push(arr[i]);
        }
    }
    
    // Sort both arrays
    evenElements.sort((a, b) => a - b);
    oddElements.sort((a, b) => a - b);
    
    // Merge back into original positions
    const result = [];
    let evenIndex = 0, oddIndex = 0;
    
    for (let i = 0; i < arr.length; i++) {
        if (i % 2 === 0) {
            result[i] = evenElements[evenIndex++];
        } else {
            result[i] = oddElements[oddIndex++];
        }
    }
    
    return result;
}

const testArray = [9, 2, 7, 4, 5, 6, 3, 8, 1];
console.log("Built-in sort result:", sortOddEvenBuiltIn(testArray));
Built-in sort result: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Time Complexity

The bubble sort approach has O(n²) time complexity in the worst case, but since we're sorting elements at even and odd positions separately, the effective comparisons are reduced. The built-in sort approach has O(n log n) complexity and is more efficient for larger arrays.

Conclusion

This algorithm maintains the relative positioning of odd and even indexed elements while sorting them independently. The bubble sort approach works well for educational purposes, while the built-in sort method is more practical for production use.

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

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements