3

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!

1
  • 2
    Store this item in a temp var, assign the next item to this item, assign the temp var to the next item... I other words: replace the current item with the next item and the next item with the current item Commented Dec 22, 2020 at 22:22

3 Answers 3

3

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].

Sign up to request clarification or add additional context in comments.

Comments

1

It is swapping the values of the current and next element inside the array.

The problem of something like this

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

is that in the first assignment you overwrite the regular value of array[i] with array[i+1] so that you would assign the same value of array[i+1] in the second line, therefore you use the temp variable to store the orginal value of array[i] to have this value after the assignment in line 1

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

In line one you basically store the orignial value of array[i] to later on reassgign array[i+1] with it

Comments

1

If you want to place a new value at a position in an array, the old value at that position will be overwritten.

const arr = [0, 1, 3, 2]

We'll use this array as an example. If I want to swap the values at arr[2] and arr[3], I could start by setting arr[2] = arr[3] resulting in the following. You'll notice that the value 3 is now missing!

 const arr = [0, 1, 2, 2]

This is why you create a temp variable. To temporarily store the value that will be overwritten. Here's an example with the index 2:

 // array = [0, 1, 3, 2]
 let temp = array[2];      
 // temp = 3
 // array = [0, 1, 3, 2]
 array[2] = array[2+1];
 // temp = 3
 // array = [0, 1, 2, 2]
 array[2+1] = temp;
 // array = [0, 1, 2, 3]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.