Search code examples
javascripthtmlalgorithmbubble-sort

Bubble sort not swapping elements of array in Javascript


I am creating a simple program that should utilize the bubble sort algorithm to sort a list of numbers in ascending order.

Just for testing purposes I have added the line alert(unsortedNumbers);and as you can see if you run it, the numbers do not change order no matter how many passes the algorithm does.

The program seems to be stuck in an infinite loop, as 'Another pass' is printed to the console repeatedly. As instructed by this line console.log("Another pass");

As with the bubble sort algorithm, once it does not have to swap any terms on a certain pass, we know this is the sorted list, I have created the variable swapped, however it looks like this is always 1. I think this may be caused by the swapArrayElements() function not swapping the terms.

Why is the function not swapping the index of the terms within the array?

(Code does't seem to run properly on SO's code snippet tool, may have to copy into notepad document)

function main(){

  var unsortedNumbers =[7,8,13,1,6,9,43,80]; //Declares unsorted numbers array
  alert(unsortedNumbers);
  var swapped = 0;
  var len = unsortedNumbers.length;

  function swapArrayElements(index_a, index_b) { //swaps swapArrayElements[i] with swapArrayElements[ii]
    var temp = unsortedNumbers[index_a];
    unsortedNumbers[index_a] = unsortedNumbers[index_b];
    unsortedNumbers[index_b] = temp;
  }

  function finish(){
    alert(unsortedNumbers);
  }

  function mainBody(){
    for(var i =0;i<len;i++){
      var ii =(i+1);
      if (unsortedNumbers[i]>unsortedNumbers[ii]){
        console.log("Swap elements");
        swapArrayElements(i,ii);
        swapped=1; // Variable 'swapped' used to check whether or not a swap has been made in each pass
      }
      if (ii = len){
        if (swapped = 1){ // if a swap has been made, runs the main body again
          console.log("Another pass");
          alert(unsortedNumbers); //Added for debugging
          swapped=0;
          mainBody();
        }else{
          console.log("Finish");
          finish();
        }
      }
    }
  }



  mainBody();
}
<head>
</head>
<body onload="main()">
</body>


Solution

  • You have an error in your code:

    if (ii = len) {
    

    and also

    if (swapped = 1){ 
    

    it should be double equal