CJamie

radixsort

Mar 24th, 2022
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. vector<int> a;
  4. void print() {
  5. cout << "state: ";
  6. for(auto x: a) {
  7. cout << x << " ";
  8. }
  9. cout << endl;
  10. }
  11. void count_sort(int n, int pos) {
  12. vector<int> b(n), count(10, 0);
  13. for (int i = 0; i < n; i++)
  14. count[(a[i] / pos) % 10]++;
  15. for (int i = 1; i < 10; i++)
  16. count[i] += count[i - 1];
  17. for (int i = n - 1; i >= 0; i--) {
  18. b[count[(a[i] / pos) % 10] - 1] = a[i];
  19. count[(a[i] / pos) % 10]--;
  20. }
  21. for (int i = 0; i < n; i++)
  22. a[i] = b[i];
  23. }
  24. void radix_sort(vector<int> a, int n) {
  25. int k = 0;
  26. for (auto x: a) k = max(k, x);
  27. for (int pos = 1; k / pos > 0; pos *= 10){
  28. cout<<"pos "<<pos<<"s"<<endl;
  29. count_sort(n, pos);
  30. print();
  31. }
  32. }
  33. int main() {
  34. int n;
  35. //cout << "enter size & elements of the array \n";
  36. cin >> n;
  37. a.resize(n);
  38. for (auto &x: a) cin >> x;
  39. radix_sort(a, n);
  40. cout << "\nradix sorted array ";
  41. for (auto x: a) cout<<x<<" ";
  42. return 0;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment