Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <stdio.h> /* printf, scanf, puts, NULL */
- #include <stdlib.h> /* srand, rand */
- #include <time.h> /* time */
- using namespace std;
- void counting_sort(vector<int> & a, vector<int> & b, int k)
- {
- int mn = *min_element(a.begin(), a.end());
- int mx = *max_element(a.begin(), a.end());
- vector<int> c(mx - mn + 1, 0);
- cout << c.size() << endl;
- for(int i = 0; i < a.size(); i++)
- {
- c[a[i] - mn]++;
- }
- for(int i = 1; i < c.size(); i++)
- {
- c[i] += c[i - 1];
- }
- for(int i = a.size() - 1; i >= 0; i--)
- {
- b[c[a[i]]] = a[i];
- c[a[i]]--;
- }
- }
- int main()
- {
- #ifdef _DEBUG
- freopen("in.txt", "r", stdin);
- freopen("out.txt", "w", stdout);
- #endif
- //Сортировка подсчетом.
- //Алгоритм сортировки применим, если каждый из n элементов сортируемой последовательности - целое положительное число <= известного k.
- //Работает за линейное время.
- srand (time(NULL));
- int n, k = -1e9; cin >> n;
- vector<int> a(n), b(n);
- for(int i = 0; i < n; i++)
- {
- a[i] = rand() % (int)1e9 - (int)1e4;
- k = max(k, a[i]);
- cout << a[i] << endl;
- }
- cout << endl;
- counting_sort(a, b, k);
- for(int i = 0; i < n; i++)
- {
- cout << b[i] << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement