Learn Basic Algorithmic Thinking by Building a Number Sorter - Step 38

Tell us what’s happening:

I am able to solve the challenge by following the instructions but I am having trouble understanding what is going on. I hope you don’t mind helping.

I don’t understand what the j-- is doing.

So here is the logic as i understand it:
currValue = 2;
array[j] = 8;
therefore: array[j] is greater than currValue;
decrement j;
j is already 0, correct? what does j-- do? j is now -1? what does that even mean?
is my logic sound?
help! :slight_smile: :slight_smile: :slight_smile:

Your code so far

<!-- file: index.html -->

/* file: styles.css */

/* file: script.js */
// User Editable Region

const insertionSort = (array) => {
  for (let i = 1; i < array.length; i++) {
    const currValue = array[i];
    let j = i - 1;

    while (j >= 0 && array[j] > currValue) {

     decrement j
    }
  }
}

// User Editable Region

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36

Challenge Information:

Learn Basic Algorithmic Thinking by Building a Number Sorter - Step 38

j-- is the equivalent of j = j - 1

So it reduces the value of j by 1

Only for the first iteration of the i loop. i keeps getting bigger though and then j starts with a new value that is 1 less than i

1 Like

If you add this to your code around where you use j-- it should help to follow the execution:

      console.log("before",j);
      j--;
      console.log("after",j);
while (j >= 0

The loop runs as long as j is 0 or higher. When j is -1 the loop ends.

1 Like

thank you. i think i understand. j gets decremented during the first iteration, but by then the loop has finished and it starts over with i being incremented. if i have that wrong please tell me. thanks for the explanation

1 Like

nice. thank you. it seems a little more obvious now

1 Like

You got it. Fun profile pic by the way - that’s a great show!

2 Likes

it was my favorite of the star treks. i think. i love them all, lol

1 Like