Advertisement
Guest User

Untitled

a guest
Dec 9th, 2016
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void quickSort(int l, int r,int *a)
  5. {
  6. int x = a[l + (r - l) / 2];
  7.  
  8. int i = l;
  9. int j = r;
  10.  
  11. while(i <= j)
  12. {
  13. while(a[i] < x) i++;
  14. while(a[j] > x) j--;
  15. if(i <= j)
  16. {
  17. swap(a[i], a[j]);
  18. i++;
  19. j--;
  20. }
  21. }
  22. if (i<r)
  23. quickSort(i, r,a);
  24.  
  25. if (l<j)
  26. quickSort(l, j,a);
  27. }
  28. void bubbleSort(int* a, int n)
  29. {
  30. for(int i = 0; i < n; ++i)
  31. for(int j = 0; j < n; ++j)
  32. if (a[j + 1] < a[j])
  33. swap(a[j+1],a[j]);
  34. }
  35. void mergeSort(int l,int r,int *a)
  36. {
  37. if(r==l)
  38. return;
  39. if(r-l == 1)
  40. if(a[r]>a[l])
  41. return;
  42.  
  43. int m = l + (r - l) / 2;
  44. mergeSort(l,m,a);
  45. mergeSort(m+1,r,a);
  46.  
  47. int buf[r+1];
  48. int xl=l;
  49. int xr=m+1;
  50. int cur = 0;
  51. while(r-l+1 != cur)
  52. {
  53. if(xl >m)
  54. buf[cur++]=a[xr++];
  55. else if(xr>r)
  56. buf[cur++]=a[xl++];
  57. else if(a[xl]>a[xr])
  58. buf[cur++]=a[xr++];
  59. else
  60. buf[cur++]=a[xl++];
  61. }
  62. for(int i = 0;i<cur;i++)
  63. a[i+l]=buf[i];
  64.  
  65. }
  66. void init(int *a,int n)
  67. {
  68. for(int i = 0; i < n; i++)
  69. {
  70. a[i] = rand()%100;
  71. }
  72. }
  73. void show(int *a,int n)
  74. {
  75. for(int i = 0; i < n; i++)
  76. {
  77. cout<<a[i]<<" ";
  78. }
  79. }
  80. int main()
  81. {
  82. srand(time(NULL));
  83. long int time[2];
  84. int n;
  85. cin >> n;
  86. int a[n];
  87.  
  88. cout << "INITED" << endl;
  89. init(a,n);
  90. // show(a,n);
  91.  
  92. cout << endl << "MergeSort ";
  93. time[0] = clock();
  94. mergeSort(0, n-1,a);
  95. time[1] = clock() - time[0];
  96. cout << "TIME: "<< ((float)time[1])/CLOCKS_PER_SEC <<endl;
  97. // show(a,n);
  98.  
  99. cout << endl << "QuickSort ";
  100. time[0] = clock();
  101. quickSort(0, n-1,a);
  102. time[1] = clock() - time[0];
  103. cout << "TIME: "<< ((float)time[1])/CLOCKS_PER_SEC <<endl;
  104. // show(a,n);
  105.  
  106. cout << endl << "BubbleSort ";
  107. time[0] = clock();
  108. bubbleSort(a,n-1);
  109. time[1] = clock()-time[1];
  110. cout << "TIME: "<< ((float)time[1])/CLOCKS_PER_SEC <<endl;
  111. // show(a,n);
  112.  
  113. return 0;
  114. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement