3 Dsa-Sorting Insertionsort
3 Dsa-Sorting Insertionsort
INSERTION SORT
SELECTION SORT
QUICK SORT
MERGE SORT
HEAP SORT
NON-COMPARISON(LINEAR) SORTING ALGORITHMS
RADIX SORT
COUNTING SORT
Problem statement
Given an application that needs sorted array
elements as input. However, all the array
elements are not available in the beginning.
Can you use bubble sort in this scenario?
4 3 2 10 12 1 5 6
Virtually split the array into a sorted and an unsorted part.
4 3 2 10 12 1 5 6
Pick one value (say key) from the unsorted part.
4 3 2 10 12 1 5 6
3 4 2 10 12 1 5 6
3 4 2 10 12 1 5 6
3 4 10 12 1 5 6
3 4 10 12 1 5 6
2 3 4 10 12 1 5 6
Sorted Unsorted
2 5 6 8 9 10 23 34 67
Worst Case: Array is reverse sorted: O(n2): When we
initiate insertion sort on a reverse-sorted array, it will insert
each element at the beginning of the sorted subarray,
making it the worst time complexity of insertion sort.
67 34 23 10 9 8 6 5 2
Test yourself
• Insertion sort comes into which category of
algorithm? Comparison based or non-
comparison algorithm.
• Is Insertion Sort an in-place sorting
algorithm?
• Is Insertion Sort a stable algorithm?
• When is the Insertion Sort algorithm used?
• Is insertion sort adaptive?
Test yourself
• Insertion sort comes into which category of
algorithm? Comparison based or non-
comparison algorithm.
• Is Insertion Sort an in-place sorting
algorithm? Yes
• Is Insertion Sort a stable algorithm? Yes
• Is insertion sort adaptive? Yes
• When is the Insertion Sort algorithm used?
When number of elements is small. When
input array is already sorted or almost sorted.
Insertion sort: Advantages
• On average, insertion performs fewer comparisons
than other quadratic sorting algorithms such as
bubble sort and selection sort.
• It is a stable sorting algorithm, as it does not change
the relative order of elements with equal values.
• It is adaptive, which means it performs a lesser
number of operations if a partially sorted array is
provided as input, making it efficient.
• It is an in-place algorithm ,requires O(1) extra space.
• It is online — it can start sorting the data even if the
entire dataset is not available right from the
beginning.
Insertion sort: Disadvantages
• Its time complexity is quadratic, so it is not
efficient for large data sets.
• Which one out of bubble, insertion and
selection sort?
• All three have quadratic complexity.