[go: up one dir, main page]

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

Experiment No.6: To Sort The Given Set of Elements Using Insertion Sort

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 4

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