Professional Documents
Culture Documents
Unit 4
Topics
• Insertion Sort
• Selection Sort
• Merge Sort
INSERTION SORT
IDEA:
At each step, the algorithm takes an element from the unsorted portion and
Take 11 from the unsorted portion, compare with 12 and insert it before
12. [11,12] is sorted, [13, 5, 6] are unsorted.
Take 13, compare with 12, insert after 12. [11, 12, 13], [5,6]
Take 5, compare with 13, 12 & 11, insert before 11. [5, 11, 12, 13], [6]
Take 6, compare with 13, 12 insert before 12. [5, 6, 11, 12, 13]
EXAMPLE:
insertion_sort:
Takes a lst as input & sorts it in-place
using insertion sort algorithm.
The outer loop iterates over the
elements of the list, starting from
second element (i=1)
The inner ’while’ loop compares the
current element (key) with the
elements before it,
Moving larger elements to the right
until the correct position for ‘key’ is
found.
The key is then placed at its correct
position in the array.
SELECTION SORT
IDEA
Select repeatedly the smallest/largest element from the unsorted portion of the
list and swaps it with the first element of unsorted part.
Divide the unsorted list into n sublists, each containing one element.
Repeatedly merge sublists to produce new sorted sublists until there is only one
sublist remaining.
MERGE SORT