The main concept behind insertion sort is to sort elements by comparison.
The comparison occurs in your case for a dataStore array, containing what we assume to be comparable elements such as numbers.
In order to compare element by element, this insertion sort algorithm starts at the beginning of the dataStore array and will continue to run until the end of the array has been reached. This is accomplished by a for loop:
for (var outer = 1; outer <= this.dataStore.length - 1; ++outer)
As the algorithm goes through each element in order, it will:
- Store the current element we are visiting in the array in a variable called
temp.
- Keep track of the location we are in the array via the
inner and outer variables, where:
outer is our counter.
inner is a flag to determine whether or not we are visiting the first element in the array. Why is this important? Because there is no point in doing a comparison on the first element, on the first try.
It will compare the current element temp with each element that came before it in the dataStore array. This is accomplished by an inner while loop as seen here:
while (inner > 0 && (this.dataStore[inner-1] >= temp))
This tells you that, as long as all previous visited elements in the dataStore array are greater than or equal to temp, our temporary variable used to store the current element; we want to swap these values.
Swapping them will accomplish the following:
- Assume all elements before
this.dataStore[inner] are greater than 10, and the currently visited element this.dataStore[inner] equals 5. This logically means that 5 needs to be at the beginning of the array. In such case we would continue to pass 5 all the way down to this.datastore[0] thanks to the while loop. Thus making 5 the first element in the array.
At the end of this swapping, the value in temp is placed accordingly to the current position we are in the array, just to remind you which position this is, it's stored the variable outer.
TLDR: I also like Justin Powell's answer as it sticks with the code, but I thought a walk through would be more useful depending on your level of understanding. I hope it helps!