CJamie

quicksort

Mar 24th, 2022
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. vector<int> a;
  4. void _swap(int &a, int &b)
  5. {
  6. printf("swapped %d & %d; ", a, b);
  7. swap(a, b);
  8. }
  9. void print()
  10. {
  11. cout << "\ncurrent state: ";
  12. for (auto x : a)
  13. cout << x << " ";
  14. cout << endl
  15. << endl;
  16. }
  17. int partition(int l, int h)
  18. {
  19. int pivot = a[l];
  20. int start = l;
  21. int end = h;
  22. printf("pivot %d -> ", pivot);
  23. while (start < end)
  24. {
  25. while (a[start] <= pivot)
  26. start++;
  27. while (a[end] > pivot)
  28. end--;
  29. if (start < end)
  30. {
  31. // printf("i & j: %d %d, ", start, end);
  32. _swap(a[start], a[end]);
  33. }
  34. }
  35. cout << " pivot ";
  36. _swap(a[l], a[end]);
  37. print();
  38. return end;
  39. }
  40. void quick_sort(int l, int h)
  41. {
  42. int loc;
  43. if (l < h)
  44. {
  45. loc = partition(l, h);
  46. quick_sort(l, loc - 1);
  47. quick_sort(loc + 1, h);
  48. }
  49. }
  50. int main()
  51. {
  52. int n;
  53. // cout << "enter size & elements of the array \n";
  54. cin >> n;
  55. a.resize(n);
  56. for (auto &x : a)
  57. cin >> x;
  58. quick_sort(0, n - 1);
  59. cout << "\n quick sorted array ";
  60. for (auto x : a)
  61. cout << x << " ";
  62. return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment