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

Tell us what’s happening:

Your code so far

What is wrong with the code

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){
      array[j + 1] = array[j];
      j--
    }

  }
}

WARNING

The challenge seed code and/or your solution exceeded the maximum length we can port over from the challenge.

You will need to take an additional step here so the code you wrote presents in an easy to read format.

Please copy/paste all the editor code showing in the challenge from where you just linked.

Replace these two sentences with your copied code.
Please leave the ``` line above and the ``` line below,
because they allow your code to properly format in the post.

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36

Challenge Information:

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

There are a couple of issues in the provided code:

  1. The decrement operator in JavaScript is --, not .
  2. The insertionSort function doesn’t return anything. Typically, sorting functions modify the input array in place, but it’s a good practice to have them return the sorted array as well.
  3. The inner while loop doesn’t update the position j correctly.

Here’s the corrected code:

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) {
array[j + 1] = array[j];
j–;
}
array[j + 1] = currValue; // Place current value in the correct position
}
return array; // Return the sorted array
}

i hope These changes will make the insertionSort function work correctly.

only the decrementing has to be added in this step, remove the other line

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.