fork download
  1. #include <stdlib.h>
  2. #include <stdint.h>
  3.  
  4. #include <time.h>
  5. #include <assert.h>
  6.  
  7. #include <algorithm>
  8. #include <iostream>
  9.  
  10. void radix_sort(uint32_t *in, uint32_t *out, int shift, int n){
  11. int index[256] = {};
  12. for (int i=0; i<n; i++) index[(in[i]>>shift)&0xFF]++;
  13. for (int i=0, sum=0; i<256; i++) sum += index[i], index[i] = sum - index[i];
  14. for (int i=0; i<n; i++) out[index[(in[i]>>shift)&0xFF]++] = in[i];
  15. }
  16. void check(int n){
  17. uint32_t *data = new uint32_t[n];
  18. uint32_t *temp = new uint32_t[n];
  19. uint32_t *same = new uint32_t[n];
  20. for (int i=0; i<n; i++) same[i] = data[i] = (rand()<<16)|rand();// Note: rand() might not produce enough randomness
  21.  
  22. clock_t t_radix = clock();
  23.  
  24. radix_sort(data, temp, 0, n);
  25. radix_sort(temp, data, 8, n);
  26. radix_sort(data, temp, 16, n);
  27. radix_sort(temp, data, 24, n);
  28.  
  29. t_radix = clock() - t_radix;
  30.  
  31. clock_t t_sort = clock();
  32.  
  33. std::sort(same, same+n);
  34.  
  35. t_sort = clock() - t_sort;
  36.  
  37. std::cout << "n: " << n << std::endl;
  38. std::cout << "radix_sort: " << t_radix << std::endl;
  39. std::cout << " std:sort: " << t_sort << std::endl;
  40. std::cout << std::endl;
  41.  
  42. for (int i=0; i<n; i++) assert(same[i] == data[i]);
  43.  
  44. delete[] data;
  45. delete[] temp;
  46. delete[] same;
  47. }
  48.  
  49. int main(){
  50. for (int i=0; i<30; i++) check(1<<i);
  51. return 0;
  52. }
  53.  
Time limit exceeded #stdin #stdout 5s 199680KB
stdin
Standard input is empty
stdout
n: 1
radix_sort: 0
  std:sort: 0

n: 2
radix_sort: 0
  std:sort: 0

n: 4
radix_sort: 0
  std:sort: 0

n: 8
radix_sort: 0
  std:sort: 0

n: 16
radix_sort: 0
  std:sort: 0

n: 32
radix_sort: 0
  std:sort: 0

n: 64
radix_sort: 0
  std:sort: 0

n: 128
radix_sort: 0
  std:sort: 0

n: 256
radix_sort: 0
  std:sort: 0

n: 512
radix_sort: 0
  std:sort: 0

n: 1024
radix_sort: 0
  std:sort: 0

n: 2048
radix_sort: 0
  std:sort: 0

n: 4096
radix_sort: 0
  std:sort: 0

n: 8192
radix_sort: 0
  std:sort: 0

n: 16384
radix_sort: 0
  std:sort: 0

n: 32768
radix_sort: 0
  std:sort: 10000

n: 65536
radix_sort: 0
  std:sort: 10000

n: 131072
radix_sort: 10000
  std:sort: 10000

n: 262144
radix_sort: 10000
  std:sort: 20000

n: 524288
radix_sort: 20000
  std:sort: 50000

n: 1048576
radix_sort: 50000
  std:sort: 90000

n: 2097152
radix_sort: 110000
  std:sort: 200000

n: 4194304
radix_sort: 220000
  std:sort: 410000

n: 8388608
radix_sort: 480000
  std:sort: 870000