dimanche 20 janvier 2019

Translate VisuAlgo Bubble Sorting code to Javascript

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 if statement, within a for loop, within a do-while loop... is that possible in Javascript? To me it looks like an if else statement within the do while (see my actual code) could replace the for.

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