starting from the SORTING algorithm I found on this website (it's really cool, it let's you visualize algorithms while they are operating..), I wanted to translate their code [and I'm not sure what language it is..] to Javascript, and apply it to an Array of numbers to be sorted.
After many attempts, I still haven't sorted it out and my code is not providing the sorted Array.
- 1) Any suggestion on how to fix it?
- 2) I see the VisuAlgo code uses an
ifstatement, within aforloop, within ado-whileloop... is that possible in Javascript? To me it looks like anif elsestatement within thedo while(see my actual code) could replace thefor.
Thank you!
VisuAlgo code (https://visualgo.net/en/sorting):
do
swapped = false
for i = 1 to indexOfLastUnsortedElement-1
if leftElement > rightElement
swap(leftElement, rightElement)
swapped = true
while swapped
My Code:
function swap(element1, element2) {
var t = element1;
element1 = element2;
element2 = t;
return [element1, element2];
};
var startArray = [2, 1, 0, 5, 1];
var swapped = true;
do {
for (i = 0; i < startArray.length; i++) {
if (startArray[i] > startArray[i+1]) {
swap(startArray[i], (startArray[i]+1));
console.log(startArray);
i++;
} else {
swapped = false;
}
}
}
while (swapped);
console.log(startArray);
Aucun commentaire:
Enregistrer un commentaire