Advertisement
kokokozhina

Untitled

Feb 10th, 2017
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <stdio.h> /* printf, scanf, puts, NULL */
  5. #include <stdlib.h> /* srand, rand */
  6. #include <time.h> /* time */
  7.  
  8. using namespace std;
  9.  
  10. void counting_sort(vector<int> & a, vector<int> & b, int k)
  11. {
  12.  
  13. int mn = *min_element(a.begin(), a.end());
  14. int mx = *max_element(a.begin(), a.end());
  15. vector<int> c(mx - mn + 1, 0);
  16. cout << c.size() << endl;
  17. for(int i = 0; i < a.size(); i++)
  18. {
  19. c[a[i] - mn]++;
  20. }
  21. for(int i = 1; i < c.size(); i++)
  22. {
  23. c[i] += c[i - 1];
  24. }
  25. for(int i = a.size() - 1; i >= 0; i--)
  26. {
  27. b[c[a[i]]] = a[i];
  28. c[a[i]]--;
  29. }
  30. }
  31.  
  32. int main()
  33. {
  34. #ifdef _DEBUG
  35. freopen("in.txt", "r", stdin);
  36. freopen("out.txt", "w", stdout);
  37. #endif
  38.  
  39. //Сортировка подсчетом.
  40. //Алгоритм сортировки применим, если каждый из n элементов сортируемой последовательности - целое положительное число <= известного k.
  41. //Работает за линейное время.
  42. srand (time(NULL));
  43. int n, k = -1e9; cin >> n;
  44. vector<int> a(n), b(n);
  45. for(int i = 0; i < n; i++)
  46. {
  47. a[i] = rand() % (int)1e9 - (int)1e4;
  48. k = max(k, a[i]);
  49. cout << a[i] << endl;
  50. }
  51. cout << endl;
  52. counting_sort(a, b, k);
  53.  
  54. for(int i = 0; i < n; i++)
  55. {
  56. cout << b[i] << endl;
  57. }
  58. return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement