Discrete mathematics practical file sem-2, Exercises of Discrete Mathematics

Practicals assignments of Discrete mathematics sem-2 university of delhi

Typology: Exercises

2019/2020

Uploaded on 09/24/2021

adeeb-ahmed-1
adeeb-ahmed-1 🇮🇳

2

(3)

4 documents

1 / 3

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
9.Write a Program to implement Insertion Sort. Find the number of comparisons during
each pass and display the intermediate result. Use the observed values to plot a graph to
analyse the complexity of algorithm.
CODE:
1) #include<iostream>
2) using namespace std;
3)
4) class insertionsort
5) {
6) int *arr;
7) int n;
8) int c;
9) public :
10) insertionsort(int size)
11) {
12) n=size;
13) arr=new int [size];
14) c=0;
15) }
16) void input();
17) void display();
18) void sort();
19) };
20)
21) void insertionsort::input()
22) {
23) cout<<"ENTER ELEMENTS OF ARRAY :"<<endl;
24) for(int i=0;i<n;i++)
25) cin>>arr[i];
26) }
27) void insertionsort::display()
28) {
29) for(int i=0;i<n;i++)
30) cout<<arr[i]<<" ";
31) cout<<endl;
32) }
33) void insertionsort::sort()
34) {
35) int key,i,j,c=0;
36) for(j=1;j<n;j++)
37) {
38) key=arr[j];
39) i=j-1;
pf3

Partial preview of the text

Download Discrete mathematics practical file sem-2 and more Exercises Discrete Mathematics in PDF only on Docsity!

9.Write a Program to implement Insertion Sort. Find the number of comparisons during each pass and display the intermediate result. Use the observed values to plot a graph to analyse the complexity of algorithm. CODE:

  1. #include
  2. using namespace std;
  3. class insertionsort
  4. {
  5. int *arr;
  6. int n;
  7. int c;
  8. public :
  9. insertionsort(int size)
  10. {
  11. n=size;
  12. arr=new int [size];
  13. c=0;
  14. }
  15. void input();
  16. void display();
  17. void sort();
  18. };
  19. void insertionsort::input()
  20. {
  21. cout<<"ENTER ELEMENTS OF ARRAY :"<<endl;
  22. for(int i=0;i<n;i++)
  23. cin>>arr[i];
  24. }
  25. void insertionsort::display()
  26. {
  27. for(int i=0;i<n;i++)
  28. cout<<arr[i]<<" ";
  29. cout<<endl;
  30. }
  31. void insertionsort::sort()
  32. {
  33. int key,i,j,c=0;
  34. for(j=1;j<n;j++)
  35. {
  36. key=arr[j];
  37. i=j-1;
  1. while(i>=0&&arr[i]>key)
  2. {
  3. c++;
  4. arr[i+1]=arr[i];
  5. i=i-1;
  6. }
  7. arr[i+1]=key;
  8. if(key>arr[i])
  9. {
  10. c++;
  11. }
  12. cout<<"INTERMIDIATE RESULT :"<<endl;
  13. for(int f=0;f<n;f++)
  14. cout<<arr[f]<<" ";
  15. cout<<endl;
  16. }
  17. cout<<"TOTAL COMPARISIONS "<<c<<endl;
  18. }
  19. int main()
  20. {
  21. int size;
  22. cout<<"ENTER SIZE :"<<endl;
  23. cin>>size;
  24. insertionsort ins(size);
  25. ins.input();
  26. cout<<"ARRAY BEFORE SORTING "<<endl;
  27. ins.display();
  28. ins.sort();
  29. } OUTPUT: