bhupixb

Just a complicated Quick sort implementation

Mar 3rd, 2020
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. // I can't tell you what it really is,
  2. // I can only tell you what it feels like.
  3. #include "bits/stdc++.h"
  4. using namespace std;
  5.  
  6. int a[10000];
  7. int iter, n;
  8.  
  9. int partition(int l, int r) {
  10. // cout << "before: ";
  11. // for (int i = l; i <= r; ++i) {
  12. // cout << a[i] << ' ';
  13. // }cout << endl;
  14. // cout << "pivot: " << a[l] << '\n';
  15. // cout << l << ' ' << r << ' ';
  16. // ++iter;
  17. // if (iter>100)exit(0);
  18. int pivot = a[l];
  19. int i = l+1;
  20. int j = r;
  21. while (i < j) {
  22. while (i < r && a[i] < pivot) ++i;
  23. while (j > l && a[j] >= pivot) --j;
  24. if (i < j) swap(a[i], a[j]);
  25. }
  26. swap(a[l], a[j]);
  27. // cout << "partition: " << j << '\n';
  28. // cout << "after: ";
  29. // for (int i = l; i <= r; ++i) {
  30. // cout << a[i] << ' ';
  31. // }cout << endl;
  32. // cout << endl;
  33. return j;
  34. }
  35.  
  36.  
  37. void quick(int lo, int hi) {
  38. if (lo >= hi) return;
  39. if (lo + 1 == hi) {
  40. if (a[lo] > a[hi]) swap(a[lo], a[hi]);
  41. return;
  42. }
  43. int p = partition(lo, hi);
  44.  
  45. quick(lo, p-1);
  46. quick(p+1, hi);
  47. }
  48.  
  49. signed main() {
  50. ios::sync_with_stdio(false);
  51. cin.tie(0);
  52. srand(time(NULL));
  53.  
  54. // n = rand() % 1000 + 1;
  55. cin >> n;
  56.  
  57. for (int i = 0; i < n; ++i)
  58. cin >> a[i];
  59. // a[i] = rand() % 10000 + 7;
  60.  
  61. random_shuffle(a, a+n);
  62. quick(0, n-1);
  63. // cout << n << '\n';
  64. for (int i = 0; i < n; ++i) {
  65. cout << a[i] << ' ';
  66. }
  67. // cout << endl;
  68. // if(!is_sorted(a, a+n)) cout << "fuck";
  69. assert(is_sorted(a, a+n));
  70. return 0;
  71. }
  72. // 1). Try forming/rearranging the equations if any
  73. // 2). If problem asks to count, try counting in reverse(it can be easier sometimes)
Add Comment
Please, Sign In to add comment