View
130
Download
0
Category
Tags:
Preview:
Citation preview
Insertion Sort
9 72 5 1 4 3 6
Insertion Sort
9 72 5 1 4 3 6
Sorted section
We start by dividing the array in a section section and an unsorted section. We put the first element as the only element in the sorted section, and the rest of the array is the unsorted section.
Insertion Sort
9 72 5 1 4 3 6
Sorted section
Item to position
The first element in the unsorted section is the next element to be put into the correct position.
Insertion Sort
9 7
2
5 1 4 3 6
Item to position
2
We copy the element to be placed into another variable so it doesn’t get overwritten.
Insertion Sort
9 7
2
5 1 4 3 62
compare
If the previous position is more than the item being placed, copy the value into the next position
Insertion Sort
9 7
2
5 1 4 3 69
If there are no more items in the sorted section to compare with, the item to be placed must go at the front.
belongs here
Insertion Sort
9 72 5 1 4 3 6
Insertion Sort
9 72 5 1 4 3 6
Insertion Sort
9 72 5 1 4 3 6
Item to position
Insertion Sort
9
7
2 5 1 4 3 67
compare
Insertion Sort
9
7
2 5 1 4 3 6
Copied from previous position
9
compare
If the item in the sorted section is less than the item to place, the item to place goes after it in the array.
belongs here
Insertion Sort
972 5 1 4 3 6
Insertion Sort
972 5 1 4 3 6
Insertion Sort
972 5 1 4 3 6
Item to position
Insertion Sort
972
5
1 4 3 65
compare
Insertion Sort
972
5
1 4 3 69
compare
Insertion Sort
972
5
1 4 3 67
compare
belongs here
Insertion Sort
972 5 1 4 3 6
Insertion Sort
972 5 1 4 3 6
Insertion Sort
972 5 1 4 3 6
Item to position
Insertion Sort
972 5
1
4 3 61
compare
Insertion Sort
972 5
1
4 3 69
compare
Insertion Sort
972 5
1
4 3 67
compare
Insertion Sort
972 5
1
4 3 65
compare
Insertion Sort
972 5
1
4 3 62
belongs here
Insertion Sort
972 51 4 3 6
Insertion Sort
972 51 4 3 6
Insertion Sort
972 51 4 3 6
Item to position
Insertion Sort
972 51
4
3 64
compare
Insertion Sort
972 51
4
3 69
compare
Insertion Sort
972 51
4
3 67
compare
Insertion Sort
972 51
4
3 6
belongs here
5
compare
Insertion Sort
972 51 4 3 6
Insertion Sort
972 51 4 3 6
Insertion Sort
972 51 4 3 6
Item to position
Insertion Sort
972 51 4
3
63
compare
Insertion Sort
972 51 4
3
69
compare
Insertion Sort
972 51 4
3
67
compare
Insertion Sort
972 51 4
3
65
compare
Insertion Sort
972 51 4
3
64
compare
belongs here
Insertion Sort
972 51 43 6
Insertion Sort
972 51 43 6
Insertion Sort
972 51 43 6
Item to position
Insertion Sort
972 51 43
6
6
compare
Insertion Sort
972 51 43
6
9
compare
Insertion Sort
972 51 43
6
7
compare
belongs here
Insertion Sort
972 51 43 6
Insertion Sort
972 51 43 6
SORTED!
Recommended