#include <iostream> #include <vector> using namespace std; class ScaleSort { public: vector<int> sortElement(vector<int> A, int n, int k) { if(n == 1){ return A; } int tmp[k]; for(int i = 0; i < k; i++){ tmp[i] = A[i]; } buildMinHeap(tmp, k); for(int i = 0; i < n-k; i++){ A[i] = tmp[0]; tmp[0] = A[i+k]; adjustMinHeap(tmp, 0, k); } for(int i = n-k; i < n; i++){ A[i] = tmp[0]; tmp[0] = tmp[--k]; adjustMinHeap(tmp, 0, k); } return A; } void adjustMinHeap(int* A, int index_node, int size){ int var_min = index_node; int left_child = index_node*2+1; int right_child = index_node*2+2; int tmp; // cout<<"left_child: "<<left_child<<endl; // cout<<"right_child: "<<right_child<<endl; // cout<<"var_min: "<<var_min<<endl; if(A[left_child] < A[var_min] && left_child < size){ var_min = left_child; } if(A[right_child] < A[var_min] && right_child < size){ var_min = right_child; } if(var_min != index_node){ tmp = A[index_node]; A[index_node] = A[var_min]; A[var_min] = tmp; adjustMinHeap(A, var_min, size); } } void buildMinHeap(int* A, int size){ for(int i = (size/2-1); i >= 0; i--){ // cout<<"i: "<<i<<endl; adjustMinHeap(A, i, size); } } }; int main() { vector<int> a; //{2,1,4,3,6,5,8,7,10,9} a.push_back(2), a.push_back(1), a.push_back(4), a.push_back(3), a.push_back(6); a.push_back(5), a.push_back(8), a.push_back(7), a.push_back(10), a.push_back(9); ScaleSort sorter; vector<int> res = sorter.sortElement(a, 10, 2); cout<<"result: "<<endl; for(int i = 0; i < res.size(); i++) cout<<res.at(i)<<" "; cout<<endl; return 0; }