fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. template<typename T>
  5.  
  6. void Firstalg(T &x, int &a, int &b, int n){
  7. a=0;
  8. b=0;
  9. for(int i=0;i<n;i++){
  10. for(int j=0; j<n-i-1; j++){
  11. a+=1;
  12. if(x[j]>x[j+1]){
  13. swap(x[j],x[j+1]);
  14. b+=1;
  15. }
  16. }
  17. }
  18. }
  19.  
  20. template<typename T>
  21. void Secondalg(T &x, int &a, int &b, int n){
  22. a=0;
  23. b=0;
  24. for(int i=1; i<n; i++){
  25. int key = x[i];
  26. int j=i-1;
  27. while(j>=0){
  28. a+=1;
  29. if(x[j]>key){
  30. x[j+1]=x[j];
  31. b+=1;
  32. j--;
  33. }else{break;}
  34. }
  35. x[j+1]=key;
  36. }
  37. }
  38.  
  39. int main() {
  40. int n, sort, comp;
  41. cin>>n;
  42. int *x = new int[n];
  43. for (int i=0; i<n; i++){
  44. cin>>x[i];
  45. };
  46.  
  47. for (int i=0; i<n; i++){
  48. cout<<x[i]<<" ";
  49. };
  50. cout<<endl;
  51. //Для векторів
  52. vector<int> myVector ={8, 9 ,4 ,0};
  53. Firstalg(myVector,sort,comp,4);
  54. for(int i: myVector)cout<<i<<" ";
  55. cout<<"\nКількість порівнянь "<<sort<<endl<<"Кількість перестановок "<<comp;
  56. Secondalg(myVector,sort,comp,4);
  57. for(int i: myVector)cout<<i<<" ";
  58. cout<<"\nКількість порівнянь "<<sort<<endl<<"Кількість перестановок "<<comp;
  59.  
  60.  
  61. /* Secondalg(x,sort,comp,n);
  62. for (int i=0; i<n; i++){
  63. cout<<x[i]<<" ";
  64. };
  65. cout<<endl;
  66. cout<<"Кількість порівнянь "<<sort<<endl<<"Кількість перестановок "<<comp;
  67.  
  68. Firstalg(x,sort,comp,n);
  69. for (int i=0; i<n; i++){
  70. cout<<x[i]<<" ";
  71. };
  72. cout<<endl;
  73. cout<<"Кількість порівнянь "<<sort<<endl<<"Кількість перестановок "<<comp;
  74.  
  75. //First Algoritm
  76. int a=0;
  77. int b=0;
  78. for(int i=0;i<n;i++){
  79. for(int j=0; j<n-i-1; j++){
  80. a+=1;
  81. if(x[j]>x[j+1]){
  82. swap(x[j],x[j+1]);
  83. b+=1;
  84. }
  85. }
  86. }
  87.  
  88. for (int i=0; i<n; i++){
  89. cout<<x[i]<<" ";
  90. };
  91. cout<<endl;
  92. cout<<"Кількість порівнянь "<<a<<endl<<"Кількість перестановок "<<b;
  93.  
  94. //Second
  95. int a=0;
  96. int b=0;
  97. for(int i=1; i<n; i++){
  98. int key = x[i];
  99. int j=i-1;
  100. while(j>=0){
  101. a+=1;
  102. if(x[j]>key){
  103. x[j+1]=x[j];
  104. b+=1;
  105. j--;
  106. }else{break;}
  107. }
  108. x[j+1]=key;
  109. }
  110.  
  111. for (int i=0; i<n; i++){
  112. cout<<x[i]<<" ";
  113. };
  114. cout<<endl;
  115. cout<<"Кількість порівнянь "<<a<<endl<<"Кількість перестановок "<<b;*/
  116.  
  117. }
Success #stdin #stdout 0s 5320KB
stdin
4 6 7 2 0
stdout
6 7 2 0 
0 4 8 9 
Кількість порівнянь 6
Кількість перестановок 50 4 8 9 
Кількість порівнянь 3
Кількість перестановок 0