Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstring>
- #include <climits>
- using namespace std;
- unsigned long long getByte(int num) {
- if (num <= 0) { return 0; }
- const int N = 256;
- unsigned long long *arr = new unsigned long long[num];
- unsigned long long N_inPower = N;
- unsigned long long sum = 1;
- for (int i = 0; i < num; ++i) {
- arr[i] = N_inPower - sum;
- N_inPower *= N;
- sum += arr[i];
- }
- long long result = arr[num - 1];
- delete[] arr;
- return result;
- }
- void CountingSort(unsigned long long *arr, int n, int r) { // r - номер байта
- const int k = 256;
- unsigned long long byte = getByte(r);
- unsigned long long prevByte = getByte(r - 1);
- int *counts = new int[k];
- for (int i = 0; i < k; ++i) counts[i] = 0;
- for (int i = 0; i < n; ++i) {
- ++counts[(arr[i] & byte) / (prevByte + 1)];
- }
- int sum = 0;
- for (int i = 0; i < k; ++i) {
- int tmp = counts[i];
- counts[i] = sum;
- sum += tmp;
- }
- unsigned long long *result = new unsigned long long[n];
- for (int i = 0; i < n; ++i) {
- result[counts[(arr[i] & byte) / (prevByte + 1)]] = arr[i];
- ++counts[(arr[i] & byte) / (prevByte + 1)];
- }
- memcpy(arr, result, n * sizeof(unsigned long long));
- delete[] result;
- delete[] counts;
- }
- void LSDSort(unsigned long long *arr, int n) {
- unsigned long long max = 0;
- for (int i = 0; i < n; ++i) {
- if (arr[i] > max) {
- max = arr[i];
- }
- }
- int r = 1;
- while (r < 9) {
- CountingSort(arr, n, r);
- ++r;
- }
- }
- int main() {
- int n;
- cin >> n;
- unsigned long long *arr = new unsigned long long[n];
- for (int i = 0; i < n; ++i) {
- cin >> arr[i];
- }
- LSDSort(arr, n);
- for (int i = 0; i < n; ++i) {
- cout << arr[i] << " ";
- }
- delete[] arr;
- return 0;
- }
Add Comment
Please, Sign In to add comment