Insertion Sort
Insertion Sort
Structures
Algorithm, Working, &
Advantages
By- Ashish Patidar
Giriraj Patidar
Introducti
on
Insertion sort is a simple sorting
algorithm that builds the final sorted
array one item at a time by
comparisons.
Insertion sort works by It is a stable sorting
iteratively inserting each algorithm, meaning
element of an unsorted that elements with
list into its correct equal values maintain
position in a sorted their relative order in
portion of the list. the sorted output.
Insertion sort is considered an “in-place” sorting
algorithm, means it doesn’t require any additional
memory space to perform its working.
Algorithm Steps
1. We have to start : element of the array as
with second
first element in the array is assumed to be sorted.
2. The element which we have to compare is put into the
int value variable.
3. Now compare second element with the first element
and if the second element is smaller than the first
element then put the second element in place of first
element.
4. Now compare 3rd element with second element and 1st
element , if the 3rd element is smaller then the 2nd
element then we have to place the 3rd element in place
of 2nd element and if the 3rd element is greater then
the 2nd element then our condition become false.
5. If the condition is false then put the element of value
variable where condition is false.
6. Repeat the process until array is sorted according to
the size of the array.
Working :
Consider an array having elements { 5, 1, 4, 3, 2 }
5 1 4 3 2
5 1 4 3 2
1 5 4 3 2
1 5 4 3 2
1 4 5 3 2
1 4 5 3 2
Working (Cont…):
1 3 4 5 2
1 3 4 5 2
1 2 3 4 5
Program for Insertion Sort
Time Complexity
1. BEST CASE : When the array elements are already sorted.
Ex :-
1 2 3 4 5 6 Number of Comparisons : 1+1+1+1+1
= 5
In terms of n = (n-1)
3 4 2 5 1 6
• Space-efficient.
Disadvantages of
Insertion Sort
• Inefficient for large lists.