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;
}
In your code please move the following code segment from inner loop (j) to outer loop (i).
See the demo
Please sort the inputArray like this:
You need to supply a custom sort function to Array.sort because Array.sort() sorts array lexicographically (in dictionary order) according to the string conversion of each element.
See a working demo here
Read up the MDN:Array.sort