function insertionSort(arr)
{
// Two loops, outer to look at each element, and inner to shift elements
// Outer loop
for (let i = 1; i < arr.length; i++) // i starts at 1 because we don't need to sort the first element
{
let key = arr[i];
let j = i - 1;
// Inner loop
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
const arr = [8, 20, -2, 4, -6];
insertionSort(arr);
console.log(arr); // [-6, -2, 4, 8, 20]
It’s working fine I just don’t understand it and I can implement it all on my own except for the while loop. I’m a beginner so please bear with me