Advertisement
darkjessy94

hybridsort senza randomized quicksort

Oct 18th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. #include <vector>
  2. #include <iostream>
  3. #include <cstdlib>
  4. #include <ctime>
  5. static const int M=10;
  6.  
  7. using namespace std;
  8.  
  9. void swap( int &A, int &B)
  10. {
  11. int t=A;
  12. A=B;
  13. B=t;
  14. }
  15.  
  16. void insertionsort (vector<int>&a, int l, int r)
  17. {
  18. int key, i;
  19. for (int j=l+1; j <= r; j++)
  20. {
  21. key = a[j];
  22. i = j-1;
  23. while ( i >= l && a[i] > key)
  24. {
  25. a[i+1]= a[i];
  26. i--;
  27. }
  28. a[i+1]=key;
  29. }
  30. }
  31. void compswap ( int &A, int &B)
  32. {
  33. if (B >A) swap(A,B);
  34. }
  35. typedef int Item;
  36. int partition(vector<int>&a, int l, int r)
  37. {
  38. int i= l-1, j=r;
  39. Item v = a.at(r);
  40. for(;;)
  41. {
  42. while(a.at(++i) < v);
  43. while(v< a.at(--j)) if (j == l) break;
  44. if (i >= j) break;
  45. swap(a.at(i),a.at(j));
  46. }
  47. swap(a.at(i),a.at(r));
  48. return i;
  49. }
  50.  
  51. void quicksort(vector<int>&a, int l, int r)
  52. {
  53. int c=r-l;
  54. if (c > M)
  55. {
  56. swap(a.at((l+r)/2),a.at(r-1));
  57. compswap(a.at(l),a.at(r-1));
  58. compswap(a.at(l),a.at(r));
  59. compswap(a.at(r-1),a.at(r));
  60. int i = partition(a,l+1,r-1);
  61. quicksort(a,l,i-1);
  62. quicksort(a,i+1,r);
  63. }
  64. }
  65.  
  66. void hybridsort(vector<int>&a, int l, int r)
  67. {
  68. quicksort (a,l,r);
  69. insertionsort (a,l,r);
  70. }
  71.  
  72.  
  73.  
  74. int main()
  75. {
  76. cout<<"Inserisci il numero di elementi da ordinare del vettore: ";
  77. int tot;
  78. cin>>tot;
  79. vector<int> arr1;
  80. int x;
  81. cout<<"Inserimento: "<<endl;
  82. for(int i=0; i < tot ; i++){
  83. cin>>x;
  84. arr1.push_back(x);
  85. }
  86. cout<<"\nQuickSort"<<endl;
  87. hybridsort(arr1,0,tot-1); //tot-1 = arr1.size()-1;
  88. for(auto z : arr1)
  89. cout<<"\n"<<z;
  90. return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement