Guest User

Untitled

a guest
Oct 23rd, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3. #include <climits>
  4.  
  5. using namespace std;
  6.  
  7. unsigned long long getByte(int num) {
  8. if (num <= 0) { return 0; }
  9.  
  10. const int N = 256;
  11. unsigned long long *arr = new unsigned long long[num];
  12.  
  13. unsigned long long N_inPower = N;
  14. unsigned long long sum = 1;
  15.  
  16. for (int i = 0; i < num; ++i) {
  17. arr[i] = N_inPower - sum;
  18. N_inPower *= N;
  19. sum += arr[i];
  20. }
  21.  
  22. long long result = arr[num - 1];
  23.  
  24. delete[] arr;
  25. return result;
  26. }
  27.  
  28. void CountingSort(unsigned long long *arr, int n, int r) { // r - номер байта
  29. const int k = 256;
  30. unsigned long long byte = getByte(r);
  31. unsigned long long prevByte = getByte(r - 1);
  32.  
  33. int *counts = new int[k];
  34. for (int i = 0; i < k; ++i) counts[i] = 0;
  35. for (int i = 0; i < n; ++i) {
  36. ++counts[(arr[i] & byte) / (prevByte + 1)];
  37. }
  38.  
  39. int sum = 0;
  40. for (int i = 0; i < k; ++i) {
  41. int tmp = counts[i];
  42. counts[i] = sum;
  43. sum += tmp;
  44. }
  45.  
  46. unsigned long long *result = new unsigned long long[n];
  47. for (int i = 0; i < n; ++i) {
  48. result[counts[(arr[i] & byte) / (prevByte + 1)]] = arr[i];
  49. ++counts[(arr[i] & byte) / (prevByte + 1)];
  50. }
  51.  
  52. memcpy(arr, result, n * sizeof(unsigned long long));
  53. delete[] result;
  54. delete[] counts;
  55. }
  56.  
  57. void LSDSort(unsigned long long *arr, int n) {
  58. unsigned long long max = 0;
  59. for (int i = 0; i < n; ++i) {
  60. if (arr[i] > max) {
  61. max = arr[i];
  62. }
  63. }
  64.  
  65. int r = 1;
  66. while (r < 9) {
  67. CountingSort(arr, n, r);
  68. ++r;
  69. }
  70. }
  71.  
  72. int main() {
  73. int n;
  74. cin >> n;
  75.  
  76. unsigned long long *arr = new unsigned long long[n];
  77. for (int i = 0; i < n; ++i) {
  78. cin >> arr[i];
  79. }
  80.  
  81. LSDSort(arr, n);
  82.  
  83. for (int i = 0; i < n; ++i) {
  84. cout << arr[i] << " ";
  85. }
  86. delete[] arr;
  87. return 0;
  88. }
Add Comment
Please, Sign In to add comment