Lecture 4 - Insertion Sort PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Design and Analysis of Algorithm Lecture # 5

Insertion Sort:
Insertion sort is a sorting algorithm that builds a final sorted array one element at a
time. While sorting is a simple concept, it is a basic principle used in complex computer
programs such as file search, data compression, and path finding.

The Sorting Problem

*permutation refers to a mathematical calculation of the number of ways a particular set can be arranged

Insertion Sort
The insertion sort algorithm iterates through an input array and removes one element
per iteration, finds the place the element belongs in the array, and then places it there.
This process grows a sorted list from left to right. The algorithm is as follows:
Design and Analysis of Algorithm Lecture # 5

Algorithm:

Best Case Analysis:


Insertion sort performs two operations: it scans through the list, comparing each pair of
elements, and it swaps elements if they are out of order. Each operation contributes to the
running time of the algorithm. If the input array is already in sorted order, insertion sort
compares O(n) elements and performs no swaps.

Therefore, in the best case, insertion sort runs in O(n) time.


Design and Analysis of Algorithm Lecture # 5

Worst and Average Case Analysis:


The worst case for insertion sort will occur when the input list is in decreasing order. To
insert the last element, we need at most n−1 comparisons and at most n−1 swaps. To
insert the second to last element, we need at most n−2 comparisons and at
most n−2 swaps, and so on.

Insertion sort has a fast best-case running time and is a good sorting algorithm to use if the
input list is already mostly sorted. For larger or more unordered lists, an algorithm with a
faster worst and average-case running time, such as mergesort, would be a better choice.

The above in insertion sort program in python


Range function is used to generate series of numbers e.g. x=range(6) will produce
numbers from 0-5
Range(start, stop, step)
Start: The number from where to start default is 0;
Stop: number to which stop. end
Step: increment, default is 1.

You might also like