Sorting Demos

Insertion Sort

Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. On a repetition, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain. Sorting is typically done in-place, by iterating up the array, growing the sorted list behind it. At each array-position, it checks the value there against the largest value in the sorted list (which happens to be next to it, in the previous array-position checked). If larger, it leaves the element in place and moves to the next. If smaller, it finds the correct position within the sorted list, shifts all the larger values up to make a space, and inserts into that correct position. (Source: Wikipedia)

Need help?

The code below is an is one way of implementing an insort sort. Read through it and try to fully understand each line! You can hover over each line for further explanation. Use the graph to watch how insert sorts work - comparing two elements at a time.

Psuedocode

Hover over lines of code for further explanation!
``` iList = array of sortable items
//current value of i = 0, j =  0
function insertSort(iList){
for(int n = 1; n < iList.length; n++){
int listTemp = ilist[n];
int i = n;
while (i > 0 && listTemp < list[i-1]){
list[i] = list[i-1];
i--;
}
list[i] = listTemp;
}
}
```

Graph Visualization

Test your understanding!

Table of Values

```Index   Value
1       8000
2       1492
3       2780
4       5000
5       702
6       2288
7       2022
8       6094
9       6973
10      153
11      347
12      4025
13      2517
14      6749
15      7507
16      1929
```