Selection Sort Algorithm in JavaScript

Here we will learn how to implement a selection sort algorithm in JavaScript.
The selection sort algorithm is an in-place comparison sort algorithm. The general idea of the selection sort is to find the minimum value in the data structure, place it in the first position, then find the second minimum value, place it in the second position, and so on.

Selection Sort Algorithm in JavaScript

function selectionSort(arr) {

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

        let min = i; //  storing the index of minimum element

        for (var j = i + 1; j < arr.length; j++) {
            if (arr[min] > arr[ j ]) {
                min = j; // updating the index of minimum element
            }
        }

        if (i !== min) {
            let temp = arr[ i ];
            arr[ i ] = arr[min];
            arr[min] = temp;
        }
    }
    return arr
}

Using Bubble Sort Algorithm

To test the selection sort algorithm, we can use the following code:
const array = [2,4,3,1,6,5,7,8,9]; 
console.log("Before selection sort - " + array);
let array1 = selectionSort(array);
console.log("After selection sort - "+ array1);

Output

Before selection sort - 2,4,3,1,6,5,7,8,9
After selection sort - 1,2,3,4,5,6,7,8,9

Demo


Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments