anon anon - 9 months ago 55
Javascript Question

Sorting Arrays (Javascript)

i'm trying to construct a code that uses the selection-sort method, but i'm having trouble. When i press my button nothing happens. I figure having a second pair of eyes on the code would help me find out what's wrong.

Is my swap() function correct? Is my select() function correct? What am I doing wrong? All help is welcome!

<input id="input1" type="number" min="5" max="1000" onchange="first(); sortButton();">

<p id="demo"></p>

<!-- button appears here, once a value is entered into the input field -->
<p id="buttons1" onclick="select();"></p>

<p id="demo2"></p>


// once input1 value changes this outputs a random value less than N (value of input1) N times, then dumps out the random numbers in id="demo"

var arr = [];
function first() {
var N = document.getElementById("input1").value;
while(arr.length < N)

{var randomnumber = Math.ceil(Math.random()*N);
arr[arr.length] = randomnumber;}
document.getElementById("demo").innerHTML = arr;}

// Once input1 value changes, this buttons appears in id="buttons"
function sortButton() {document.getElementById("buttons1").innerHTML =
'<button type="button" onclick="select();">Select Sort</button>';}

function swap(arr, i, min) {
var temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;}

// meant to sort (selection sort method) the random numbers in id="demo" once the button is clicked

function select() {var len = arr.length, min, i, j;
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;}


Answer Source

Your select function is a mess. Theres a standard function called sort, that does that for you:

function select(){
 //if a<b keep it, if not swap
   return 0;
   return 1;

You can even short it:

function select(){

(See arrow functions for more info)