8-Sorting Algorithms A) Insertion Sort
8-Sorting Algorithms A) Insertion Sort
Insertion Sort
This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is
always sorted. For example, the lower part of an array is maintained to be sorted. An element
which is to be inserted in this sorted sub-list, has to find its appropriate place and then it has to
be inserted there. Hence the name, insertion sort. The array is searched sequentially and
unsorted items are moved and inserted into the sorted sub-list (in the same array). This algorithm
is not suitable for large data sets.
Insertion sort iterates, consuming one input element each repetition, and growing a sorted
output list. At each iteration, insertion sort removes one element from the input data, finds the
location it belongs within the sorted list, and inserts it there. It repeats until no input elements
remain.
2
Data Structure & Algorithms
Algorithm
1 for j ← 2 to length[A]
2 do key ← A[ j]
6 do A[i + 1] ← A[i]
7i←i−1
8 A[i + 1] ← key
Step 4 − Shift all the elements in the sorted sub-list that is greater than the value to be sorted
Implementation in C++
int ar[5], length, temp, i, j;
length = 5;
cin>>ar[i];
{
3
Data Structure & Algorithms
temp = ar[i];
j=i-1;
while(temp<ar[j] && j>=0)
ar[j+1] = ar[j];
j--;
}
ar[j+1]=temp;
cout<<ar[i]<<"\t";
}