Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Hostgator 1 Penny

BlueHost Web Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

getflywheel wordpress hosting


Distribute your Resume to 500+ Job Boards & Recruiters


7,621 questions

10,674 answers

573 users

How to implement selection sort in JavaScript

1 Answer

0 votes
function swap(arr, i, j) {
    var tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
 
function selection_sort(arr) {
    var len = arr.length, min;

    for (i=0; i < len; i++) {
        min = i;
        for (j= i + 1; j < len; j++) {
            if (arr[j] < arr[min]){
                min = j;
            }
        }
        if (i != min){
            swap(arr, i, min);
        }
    }

    return arr;
}

var arr = [];
for (var i = 0; i < 20; i++) 
    arr.push(Math.floor(Math.random() * 1000))

arr = selection_sort(arr);

for (var i = 0; i < arr.length; i++)
    document.write(arr[i] + "</br>");
 
     
/*
run:
  
53
68
83
84
120
213
233
314
430
447
510
535
545
625
696
707
728
911
977
994
   
*/

 




answered May 12 by avibootz
...