Skip to main content

Selection Sort Algorithm Using JavaScript

Here I will explain how to sort array element.

function SelectionSortAlgorithm(input) {  
    for (var i = 0; i < input.length; i++) {  
        var str = input[i];  
        for (var j = i + 1; j < input.length; j++) {  
            if (str > input[j]) {  
                str = input[j];  
            }  
        }  
        var index = input.indexOf(str);  
        var strVal = input[i];  
        input[i] = str;  
        input[index] = strVal;  
    }  
} 

var input = [11,44,7,3,2,5,8,4,0,1,16,9];  
console.log(input);  
SelectionSortAlgorithm(input);  
console.log(input); 

Output:

[44, 16, 11, 9, 8, 7, 5, 4, 3, 2, 1, 0]
[0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 16, 44] 

Comments