-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsertionSort.cpp
72 lines (72 loc) · 2.09 KB
/
InsertionSort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include<iostream>
#include<cstdlib>
#include<time.h>
using namespace std;
void insertionsort(int a[],int n,int count,int ch)
{
int v,j;
for(int i=1;i<n;i++)
{
v=a[i];
j=i-1;
while(j>=0 && a[j]>v)
{
a[j+1]=a[j];
j--;
count=count+2;
}
if((j>=0 && a[j]<=v)||(j<0 && a[j]<=v))
count++;
a[j+1]=v;
}
for(int i=0;i<n;i++)
cout<<a[i]<<"\t";
if(ch==1)
cout<<"\nNumber of comparisions in ascending order = "<<count<<"\n";
else if(ch==2)
cout<<"\nNumber of comparisions in descending order = "<<count<<"\n";
else
cout<<"\nNumber of comparisions in random order = "<<count<<"\n";
}
int main()
{
int ch,n,count=0;
do
{
cout<<"1.Ascending Order \n2.Descending Order \n3.Random Order \n4.Exit\nEnter your choice\n";
cin>>ch;
switch(ch)
{
case 1:{cout<<"Enter no of elements\n";
cin>>n;
int a[n];
for(int i=1;i<=n;i++)
a[i-1]=i;
insertionsort(a,n,count,1);
break;
}
case 2:{cout<<"Enter no of elements\n";
cin>>n;
int a[n],k=0;
for(int i=n;i>=0;i--)
{
a[k]=i;
k++;
}
insertionsort(a,n,count,2);
break;
}
case 3:{cout<<"Enter no of elements\n";
cin>>n;
int a[n];
srand(time(NULL));
for(int i=0;i<n;i++)
a[i]=rand()%n;
insertionsort(a,n,count,3);
break;
}
case 4:{exit(0);break;}
}
}while(1);
return 0;
}