Professional Documents
Culture Documents
Lab 1
Lab 1
ASSIGNMENT – 1
IPS-1 INSERTION SORT
SUBJECT: DAA Lab
COURSE CODE: BCSE204P
FACULTY NAME: Dr. Pandiyaraju V Sir
LAB SLOT: L25+L26
Aim
To implement Insertion sort algorithm in C++ Using STL and without STL and
compute the time complexity of both algorithms by varying the input sizes.
Algorithm
INSERTION-SORT(A)
1. for j =2 to A.length
2. key = A[ j ]
3. //Insert A[ j ] into the sorted sequence A[0, .. j-1].
4. i=j–1
5. while i > 0 and A [ i ] > key
6. A[ i +1 ] = A[ i ]
7. i = i -1
8. A [i +1] = key
Illustration
CODE
Implementation Of Insertion Sort Algorithm using STL and
without STL
Code:
#include<iostream>
#include<vector>
#include<ctime>
using namespace std;
int main()
{
vector<int> elements;
int key,i,j,n,ele;
//cout<<"Enter number of elements";
cin>>n;
for(i=0;i<n;i++)
{
cin>>ele;
elements.push_back(ele);
}
clock_t tStart = clock();
for(j=1;j<n;j++)
{
key = elements[j];
i = j-1;
while((i>=0)&&(elements[i]>key))
{
elements[i+1] = elements[i];
i = i-1;
}
elements[i+1] = key;
}
double time1=(double)(clock() - tStart)/CLOCKS_PER_SEC;
cout<<"Time taken is "<<time1<<endl;
/*for(i=0;i<n;i++)
{
cout<<elements[i]<<" ";
}*/
}
CODE:
Time Complexity
CODE:
Time Complexity
For Input value n=5000
Time taken is 0.062754
CODE:
OUTPUT:
Time Complexity
CODE:
#include<iostream>
using namespace std;
#include<vector>
#include<math.h>
class point
{
int x,y;
public:
bool operator>(point);
friend istream& operator>>(istream&,point&);
friend ostream& operator<<(ostream&,point&);
};
bool point::operator>(point p)
{
float dis1,dis2;
dis1 = sqrt(x*x+y*y);
dis2 = sqrt(p.x*p.x+p.y*p.y);
return (dis1>dis2);
}
istream& operator>>(istream& in, point &p)
{
in>>p.x>>p.y;
return in;
}
ostream& operator<<(ostream& out,point &p)
{
out<<p.x<<" "<<p.y<<endl;
return out;
}
int main()
{
vector<point> elements;
point key,ele;
int i,j,n;
//cout<<"Enter number of elements";
cin>>n;
for(i=0;i<n;i++)
{
cin>>ele;
elements.push_back(ele);
}
for(j=1;j<n;j++)
{
key = elements[j];
i = j-1;
while((i>=0)&&(elements[i]>key))
{
elements[i+1] = elements[i];
i = i-1;
}
elements[i+1] = key;
}
for(i=0;i<n;i++)
{
cout<<elements[i]<<" ";
}
}
CODE:
For Input value n=50
n=50
fp = open("ascending_"+str(n)+".txt","w")
fp.write(str(n)+" ")
for i in range(1,n):
fp.write(str(i)+" ")
fp.write(str(n))
fp.close()
OUTPUT:
CODE:
OUTPUT:
Conclusion:
In this Assignment we have learned about Insertion sort and implemented
Insertion sort in c++ language and we have done analysis on Insertion sort by
varying the input size and calculated time complexity for different input sizes
for three cases i.e., If the numbers are in Ascending order, Descending order
and Random order. We have Plotted graph for Time Complexity vs Input n for
all three cases.