0% found this document useful (0 votes)
107 views4 pages

Insertion Sort Algorithm Explained

The document describes insertion sort, an algorithm for sorting a list of elements. It provides the steps of the algorithm, which are to start with the first element as sorted and iteratively pick the next element, compare it to sorted elements, shift greater elements, and insert the element. A flowchart and C++ code implementing the algorithm are also included.

Uploaded by

Amitabh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
107 views4 pages

Insertion Sort Algorithm Explained

The document describes insertion sort, an algorithm for sorting a list of elements. It provides the steps of the algorithm, which are to start with the first element as sorted and iteratively pick the next element, compare it to sorted elements, shift greater elements, and insert the element. A flowchart and C++ code implementing the algorithm are also included.

Uploaded by

Amitabh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

DS LAB CSP(209)

Experiment No.6

To sort the given set of elements using Insertion Sort:

Algorithm
Insertion Sort
Start
Step 1 If it is the first element, it is already sorted. return 1;
Step 2 Pick next element
Step 3 Compare with all elements in the sorted sub-list
Step 4 Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 Insert the value
Step 6 Repeat until list is sorted

Step 9: END

Flowchart:

Navneet Gupta
16BCS1170
DS LAB CSP(209)

Navneet Gupta
16BCS1170
DS LAB CSP(209)

CODE

#include<iostream>
using namespace std;
int main()
{
int n,i,j,ctr,temp;
cout<<"Enter the size of the array :: "<<endl;
cin>>n;
cout<<"Enter the elements of the array :: "<<endl;
int ar[n];
for(i=0;i<n;i++)
{
cin>>ar[i];
}
for(i=1;i<n;i++)
{
temp=ar[i];
ctr=i-1;
while(temp<ar[ctr] && ctr>=0)
{
ar[ctr+1]=ar[ctr];
ctr=ctr-1;
}
ar[ctr+1]=temp;
}
for(i=0;i<n;i++)
{
cout<<ar[i]<<"\t";
}

return 0;
}

Navneet Gupta
16BCS1170
DS LAB CSP(209)

Output:

Navneet Gupta
16BCS1170

You might also like