I am trying to use a selection sort for javascript but it does not seem to work, can somebody help me please? I create a function to sort an array, then I get the value from the text box, and store it in an array named inputString then I split the array by comma, and store it in an array named inputNumbers If in my text box exist non number, an error will be displayed otherwise display the sorted value.
function sortNow(form) {
var nanExists = false;
var inputString = document.getElementById("numberID").value;
var inputNumbers = inputString.split(",");
for (var a = 0; a < inputNumbers.length; a++) {
inputNumbers[a] = parseInt(inputNumbers[a], 10);
if (isNaN(inputNumbers[a])) {
nanExists = true;
break;
}
}
inputNumbers = selectionSort(inputNumbers); //sort the array inputNumbers
if (nanExists)
form.answers.value = "Invalid Input";
else
{
for(var b=0; b < inputNumbers.length; b++)
{
form.answers.value += inputNumbers[b];
}
}
}
/* function to sort an array */
function selectionSort(inputArray) {
for(var i=0; i<inputArray.length; i++)
{
var currentMin = inputArray[i];
var currentMinIndex = i;
for(var j=i+1; j<inputArray.length; j++)
{
if(currentMin > inputArray[j])
{
currentMin = inputArray[j];
currentMinIndex = j;
}
if(currentMinIndex != i)
{
inputArray[currentMinIndex] = inputArray[i];
inputArray[i] = currentMin;
}
}
}
return inputArray;
}
Array.sort()?