Advertisement
_takumi

c2b2023

Jan 31st, 2023
620
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3.  
  4. int getByte(int x, int num) {
  5.     for (int i = 0; i < 3 - num; i++) {
  6.         x /= 256;
  7.     }
  8.     return (x & 0x000000FF);
  9. }
  10.  
  11. void countingSort(int *arr, int n, int num_byte) {
  12.     const size_t size = 256;
  13.     int cnt[size];
  14.    
  15.     for (int &i : cnt) {
  16.         i = 0;
  17.     }
  18.     int res[n];
  19.     memcpy(res, arr, sizeof(int) * n);
  20.     for (int i = 0; i < n; ++i) {
  21.         ++cnt[getByte(arr[i], num_byte)];
  22.     }
  23.     for (int i = 1; i < size; ++i) {
  24.         cnt[i] += cnt[i - 1];
  25.     }
  26.     for (int i = n - 1; i >= 0; --i) {
  27.         res[cnt[getByte(arr[i], num_byte)] - 1] = arr[i];
  28.         --cnt[getByte(arr[i], num_byte)];
  29.     }
  30.     memcpy(arr, res, sizeof(int) * n);
  31. }
  32.  
  33. void radixSort(int *arr, int n) {
  34.     for (int i = 3; i > 0; i--) {
  35.         countingSort(arr, n, i);
  36.     }
  37. }
  38.  
  39. int main() {
  40.     int n = 0;
  41.     std::cin >> n;
  42.     int a[n];
  43.     for (int i = 0; i < n; ++i) {
  44.         std::cin >> a[i];
  45.     }
  46.     radixSort(a, n);
  47.     for (int i = 0; i < n; ++i) {
  48.         std::cout << a[i] << " ";
  49.     }
  50.     return 0;
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement