Experiment 1: Aim: Theory
Experiment 1: Aim: Theory
Experiment 1: Aim: Theory
Roll number 33
Experiment 1
We assume that the first card is already sorted then, we select an unsorted card. If the
unsorted card is greater than the card in hand, it is placed on the right otherwise, to the left.
In the same way, other unsorted cards are taken and put at their right place.
Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in
each iteration.
1. The first element in the array is assumed to be sorted. Take the second element and
store it separately in key.
Compare key with the first element. If the first element is greater than key,
then key is
placed in front of the first element. If the first element is greater than key, then key
is placed in front of the first element
1|Page
Riddhi More
Roll number 33
Take the third element and compare it with the elements on the left of it. Placed it
just behind the element smaller than it. If there is no element smaller than it, then
place it at the beginning of the array.
Algorithm:
insertionSort(array)
mark first element as sorted
for each unsorted element X
'extract' the element X
for j <- lastSortedIndex down to 0
if current element j > X
move sorted element to the right by 1
break loop and insert X here
end insertionSort
2|Page
Riddhi More
Roll number 33
Program:
#include <iostream>
using namespace std;
// Compare key with each element on the left of it until an element smalle
r than
// it is found.
// For descending order, change key<array[j] to key>array[j].
while (key < array[j] && j >= 0) {
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}
3|Page
Riddhi More
Roll number 33
Output:
When the array is already sorted
4|Page
Riddhi More
Roll number 33
Analysis:
Time Complexities
Each element has to be compared with each of the other elements so, for every nth
element, (n-1) number of comparisons are made.
5|Page