-
Notifications
You must be signed in to change notification settings - Fork 17
/
ds question 9.cpp
71 lines (66 loc) · 1.04 KB
/
ds question 9.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
#include<iostream>
using namespace std;
class Insertionsort
{
int *arr;
int n;
int c;
public :
Insertionsort(int size)
{
n=size;
arr=new int [size];
c=0;
}
void input();
void display();
void sort();
};
void Insertionsort::input()
{
cout<<"Enter the elements in the array"<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];
}
void Insertionsort::display()
{
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
void Insertionsort::sort()
{
int key,i,j,c=0;
for(j=1;j<n;j++)
{
key=arr[j];
i=j-1;
while(i>=0&&arr[i]>key)
{
c++;
arr[i+1]=arr[i];
i=i-1;
}
arr[i+1]=key;
if(key>arr[i])
{
c++;
}
cout<<"Intermediate result"<<endl;
for(int f=0;f<n;f++)
cout<<arr[f]<<" ";
cout<<endl;
}
cout<<"The total number of comparisons are "<<c<<endl;
}
int main()
{
int size;
cout<<"Enter the size of the array"<<endl;
cin>>size;
Insertionsort ins(size);
ins.input();
cout<<"Array before sorting "<<endl;
ins.display();
ins.sort();
}