fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. mt19937_64 rd(time(0));
  5. int rand(int L, int R){
  6. return L + rd() % (R - L + 1);
  7. }
  8.  
  9. int n;
  10. vector<int> arr;
  11.  
  12. vector<int> pyramid_sort(vector<int>& arr, int length, int stage){
  13. if(length <= 1) return arr;
  14. if(length == 2){
  15. if(arr[0] < arr[1]) swap(arr[0], arr[1]);
  16. return arr;
  17. }
  18.  
  19. const int range = (length/stage == 0 ? 1 : length/stage);
  20. const int numSegments = (length - 1)/range + 1;
  21.  
  22. int times[numSegments]; memset(times, 0, sizeof times);
  23. vector<int> newVector[numSegments];
  24. vector<int> resultVector;
  25.  
  26. for(int i = 0; i < numSegments; i++){
  27. for(int j = 0; j < range; j++){
  28. if(i*range + j >= length) break;
  29.  
  30. newVector[i].push_back(arr[i*range + j]);
  31. }
  32.  
  33. newVector[i] = pyramid_sort(newVector[i], newVector[i].size(), stage + 1);
  34. }
  35.  
  36. while(resultVector.size() < length){
  37. int cur_index = 0;
  38. int cur_value = (int) -1e9;
  39.  
  40. for(int i = 0; i < numSegments; i++){
  41. if(times[i] >= newVector[i].size()) continue;
  42.  
  43. if(cur_value <= newVector[i][times[i]]){
  44. cur_value = newVector[i][times[i]];
  45. cur_index = i;
  46. }
  47. }
  48.  
  49. resultVector.push_back(cur_value);
  50. times[cur_index]++;
  51. }
  52.  
  53. return resultVector;
  54. }
  55.  
  56. bool isSorted(){
  57. for(int i = 1; i < n; i++){
  58. if(arr[i - 1] < arr[i]) return 0;
  59. }
  60.  
  61. return 1;
  62. }
  63.  
  64. int main(){
  65. ios_base::sync_with_stdio(0);
  66. cin.tie(0); cout.tie(0);
  67.  
  68. cin >> n;
  69. for(int i = 0; i < n; i++){
  70. int value; cin >> value;
  71. arr.push_back(value);
  72. }
  73.  
  74. while(!isSorted()){
  75. arr = pyramid_sort(arr, n, 2);
  76. }
  77.  
  78. for(int i = 0; i < n; i++) cout << arr[i] << ' ';
  79.  
  80. return 0;
  81. }
  82.  
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
Standard output is empty