# Errata: Data Structures and Algorithms Book!

**URL:** https://forum.kirupa.com/t/errata-data-structures-and-algorithms-book/663668
**Category:** programming
**Created:** [December 15, 2023, 3:54am UTC](https://forum.kirupa.com/t/errata-data-structures-and-algorithms-book/663668 "2023-12-15T03:54:20Z")
**Posts on this page:** 1
**Showing post:** 5

<div class="post-metadata">

### Author: ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)
#### Post date: [December 16, 2023, 3:15am UTC](https://forum.kirupa.com/t/errata-data-structures-and-algorithms-book/663668/5 "2023-12-16T03:15:56Z")

</div>

**Insertion Sort - Fixed undeclared j variable**  
The following code declares the `j` variable correctly to avoid any out-of-scope errors:

```auto
function insertionSort(input) {
  // Variable to store the current element being compared
  let activeNumber;

  // Loop through the array starting from the second element (index 1)
  for (let i = 1; i < input.length; i++) {
    // Store the current element in the activeNumber variable
    activeNumber = input[i];

    let j;
    
    // Inner loop to compare the activeNumber with the elements before it
    for (j = i - 1; j >= 0; j--) {
      if (input[j] > activeNumber) {
        // Move the greater element one position ahead to make space 
        // for the activeNumber
        input[j + 1] = input[j];
      } else {
        // If we find an element that is smaller than or 
        // equal to the activeNumber, exit the inner loop
        break;
      }
    }
    // Place the activeNumber in its correct sorted position
    input[j + 1] = activeNumber;
  }
}

let myinput = [24, 10, 17, 9, 5, 9, 1, 23, 300];
insertionSort(myinput);

console.log(myinput);

```

Thanks to @transbot for finding this one as well! 🙂

---

_[View the full topic](https://forum.kirupa.com/t/errata-data-structures-and-algorithms-book/663668)._
