Search code examples
javascriptbubble-sort

Bubble Sort Algorithm in Javascript


I have this Bubble Sort algorithm here

let bubbleSort = (array) => {
  for (let j=0;j<array.length;j++) {
    for (let i=0;i<array.length;i++) {
      if(array[i] > array[i+1]) {
      let temp = array[i];
      array[i] = array[i+1];
      array[i+1] = temp;
      }
     }
    }
   return array;
  }

I understand how it works, but I don't understand what the if statement means:

      let temp = array[i];
      array[i] = array[i+1];
      array[i+1] = temp;

Edit: I can't mark all answers as solved, but they helped me. Thank you!


Solution

  • The three lines swap the elements indexed by i and i+1.

    You can not just write

    array[i] = array[i+1];
    array[i+1] = array[i];
    

    to swap the elements because in this version, after executing the first line, the original value of array[i] is lost, as it has been overwritten with the value array[i+1].

    To fix this problem, the value array[i] can be stored in a temporary variable (called temp here) such that it can later be assigned to array[i+1].