JavaScript Program to Implement Selection Sort

JavaScript Program to Implement Selection Sort

Selection Sort is another simple and beginner-friendly sorting algorithm that helps new learners understand how sorting works in JavaScript. The main idea of Selection Sort is very easy to follow. It works by finding the smallest value in an array and placing it at the correct position, then repeating the same process for the remaining part of the array. Step by step, the array becomes sorted.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Even though Selection Sort is not the fastest algorithm, it is very useful for learning purposes. It is commonly taught in classrooms and beginner coding tutorials because its logic is clear and predictable. By learning how to write a JavaScript program to implement Selection Sort, beginners can build strong basics that make it easier to learn more advanced sorting algorithms later.

Program 1: Selection Sort using simple nested loops

This program shows the most basic and traditional way to implement Selection Sort in JavaScript. It uses two loops to find the smallest element and place it in the correct position.

let numbers = [64, 25, 12, 22, 11];

for (let i = 0; i < numbers.length; i++) {

    let minIndex = i;

    for (let j = i + 1; j < numbers.length; j++) {

        if (numbers[j] < numbers[minIndex]) {
            minIndex = j;
        }

    }

    let temp = numbers[i];
    numbers[i] = numbers[minIndex];
    numbers[minIndex] = temp;

}

console.log("Sorted array:", numbers);

This program works by first assuming the current position has the smallest value. It then checks the rest of the array to find a smaller value if one exists. Once the smallest value is found, it swaps it with the current position. Beginners like this approach because it clearly shows how selection and swapping happen in a clean and structured way.

Program 2: Selection Sort with reduced swaps

This version of Selection Sort avoids unnecessary swaps by checking if the minimum value actually needs to be moved. It makes the logic slightly more efficient while keeping it easy to read.

let values = [29, 10, 14, 37, 13];

for (let i = 0; i < values.length - 1; i++) {

    let minIndex = i;

    for (let j = i + 1; j < values.length; j++) {

        if (values[j] < values[minIndex]) {
            minIndex = j;
        }

    }

    if (minIndex !== i) {

        let temp = values[i];
        values[i] = values[minIndex];
        values[minIndex] = temp;

    }

}

console.log("Sorted array:", values);

Here, the program checks whether the smallest value is already in the correct position before swapping. This helps beginners understand that small improvements can make code cleaner and more efficient. It also reinforces the idea that Selection Sort focuses on selecting the minimum value each time.

Program 3: Selection Sort using recursion

This program uses recursion instead of loops to perform Selection Sort. It is useful for learners who want to understand how sorting can be done using function calls.

let data = [20, 12, 10, 15, 2];

function selectionSortRecursive(arr, start) {

    if (start >= arr.length - 1) {
        return;
    }

    let minIndex = start;

    for (let i = start + 1; i < arr.length; i++) {

        if (arr[i] < arr[minIndex]) {
            minIndex = i;
        }

    }

    let temp = arr[start];
    arr[start] = arr[minIndex];
    arr[minIndex] = temp;

    selectionSortRecursive(arr, start + 1);

}

selectionSortRecursive(data, 0);

console.log("Sorted array:", data);

This recursive version sorts one position at a time and then calls itself for the next position. Each call places the correct smallest value at the front of the remaining array. Beginners can use this example to learn recursion while still working with a familiar sorting algorithm.

Program 4: Selection Sort in descending order

This example sorts the array from largest to smallest instead of the usual smallest to largest. It helps beginners understand how changing conditions affects the output.

let scores = [45, 89, 12, 33, 67];

for (let i = 0; i < scores.length; i++) {

    let maxIndex = i;

    for (let j = i + 1; j < scores.length; j++) {

        if (scores[j] > scores[maxIndex]) {
            maxIndex = j;
        }

    }

    let temp = scores[i];
    scores[i] = scores[maxIndex];
    scores[maxIndex] = temp;

}

console.log("Sorted array (descending):", scores);

In this program, the logic is almost the same as regular Selection Sort, but it looks for the largest value instead of the smallest. This example is useful because it shows how flexible Selection Sort is and how easily it can be adapted for different sorting needs.

Program 5: Selection Sort using a helper function

This version separates the sorting logic into a function, making the code more reusable and easier to understand for beginners.

function selectionSort(arr) {

    for (let i = 0; i < arr.length; i++) {

        let minIndex = i;

        for (let j = i + 1; j < arr.length; j++) {

            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }

        }

        let temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;

    }

    return arr;

}

let items = [9, 5, 1, 4, 3];

console.log("Sorted array:", selectionSort(items));

This program places Selection Sort inside a function so it can be reused with different data. Beginners often find this approach helpful because it shows how algorithms are commonly written in real JavaScript programs. It also makes testing and practicing easier.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Selection Sort in JavaScript in a simple and clear way.

Q1. What is Selection Sort in JavaScript?
Selection Sort is a simple sorting algorithm that repeatedly selects the smallest or largest value and places it in the correct position. In JavaScript, it is mainly used for learning and practice.

Q2. Is Selection Sort better than Bubble Sort?
Selection Sort usually performs fewer swaps than Bubble Sort, but both are slow for large arrays. They are mainly used to understand sorting basics.

Q3. Where is Selection Sort used in real life?
Selection Sort is rarely used in real applications because faster algorithms exist. However, it is widely used in teaching and interviews.

Q4. Can Selection Sort work with strings?
Yes, Selection Sort can sort strings if proper comparisons are used. JavaScript allows string comparison, making it possible.

Q5. Should beginners learn Selection Sort?
Yes, Selection Sort is excellent for beginners. It teaches careful comparison and position selection, which are important programming concepts.

Conclusion

Selection Sort is a simple and powerful learning tool for anyone starting with JavaScript. It teaches how to compare values, track positions, and swap elements step by step. By exploring different versions like loops, recursion, and descending order, beginners can gain confidence and deeper understanding.

The best way to master Selection Sort is through practice. Try changing the numbers, sorting strings, or writing your own version from scratch. With regular practice, you will be ready to move on to faster and more advanced sorting algorithms in JavaScript.

Scroll to Top