- the second element to the last element.
- For each element at index
i, the algorithm picks the current element (currentElement) and starts a loop (j) to compare it with the elements to its left (elements at indicesj - 1). - The inner loop (
j) continues as long asjis greater than 0 and the element atarr[j - 1]is greater thancurrentElement. This loop helps to find the correct position forcurrentElementwithin the sorted sequence. - Inside the inner loop, the algorithm shifts the larger elements to the right (
arr[j] = arr[j - 1]) until it finds the correct position forcurrentElement. - Once the correct position is found (
jreaches the correct index), the algorithm placescurrentElementat that position (arr[j] = currentElement).
Here's the JavaScript implementation of the insertion sort algorithm using two counters: