Insertion Sort

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 9

INSERTION SORT

Insertion Sort
• Insertion sort is the algorithm very
commonly used by people playing cards to
sort the hand they have been dealt.
Imagine you have been given five cards
face down and you want to sort them
according to the following rules:
Insertion Sort
• An insertion sort works by dividing the data into
two groups: already sorted items and unsorted
items. Initially, the sorted group is empty and the
unsorted group contains all the items.
• One by one, an item is taken from the unsorted
group and inserted at the appropriate position in
the growing group of sorted items.
• Eventually, all of the items are in the sorted
group and the unsorted group is empty.
Insertion Sort
example 2
• 37495261 (3 sorted)
• 37495261 (3 and 7 sorted)
• 37495261 (4 < 7 ; 4 > 3 inserts in place)
• 34795261 (3,4,7 now sorted)
• 34795261
• 34579261
• 23457961
• 23456791
• 12345679
Insertion Sort
Comparisons
• Insertion sort's advantage is that it only
scans as many elements as needed to
determine the correct location of the k+1st
element, while selection sort must scan all
remaining elements to find the absolute
smallest element.
Use Insertion sort to sort the following
numbers, and show your steps clearly:
75, 23, 56, 17, 59, 83, 12, 9, 18, 3
23, 75, 56, 17, 59, 83, 12, 9, 18, 3
23, 56, 75, 17, 59, 83, 12, 9, 18, 3
17, 23, 56, 75, 59, 83, 12, 9, 18, 3
17, 23, 56, 59, 75, 83, 12, 9, 18, 3
17, 23, 56, 59, 75, 83, 12, 9, 18, 3
12, 17, 23, 56, 59, 75, 83, 9, 18, 3
9, 12, 17, 23, 56, 59, 75, 83,18, 3
9, 12, 17, 18, 23, 56, 59, 75,83, 3
3, 9, 12, 17,18, 23, 56, 59,75,83
THE END

You might also like