Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- struct Heap {
- std::vector<int> saver;
- void swap(int& first, int& second) {
- auto bufer = second;
- second = first;
- first = bufer;
- }
- void sift_up(int index) {
- auto index_parent = (index-1)/2;
- while(index_parent >= 0){
- if( saver[index] > saver[index_parent]) {
- swap(saver[index], saver[index_parent]);
- index = index_parent;
- index_parent = (index-1)/2;
- } else {
- break;
- }
- }
- }
- void sift_down(int index) {
- auto left_index = 2*index + 1;
- auto right_index = 2*index + 2;
- while (TRUE) {
- if (left_index >= saver.size()) {
- break;
- } else if (right_index >= saver_size){
- auto change_index = left_index;
- } else if (saver[left_index] < saver[right_index]){
- auto change_index = left_index;
- } else {
- auto change_index = right_index;
- }
- if (saver[change_index] > saver[index]) {
- swap(saver[change_index], saver[index]);
- index = change_index;
- } else {
- break;
- }
- }
- }
- void insert(int x) {
- saver.push_back(x);
- auto x_index = saver.size() - 1;
- sift_up(x_index);
- }
- int get_min() {
- return saver[0];
- }
- void extract_min() {
- swap(saver[0],saver[saver.size()-1]);
- saver.pop_back();
- sift_down(0);
- }
- void make_heap(std::vector<int> array) {
- int index = array.size()/2;
- while(index >= 0){
- sift_down(index);
- index = index - 1;
- }
- }
- }
- std::vector<int> psevdo_heap_sort(std::vector<int> array) {
- Heap myheap;
- for(int& el : array) {
- myheap.insert(el);
- }
- std::vector<int> output_array;
- for(int i = 0; i < array.size(); ++i){
- output_array.push_back(myheap.get_min());
- }
- return output_array;
- }
- std::vector<int> heap_sort(std::vector<int> array) {
- Heap myheap;
- myheap.make_heap(array);
- std::vector<int> output_array;
- for(int i = 0; i < array.size(); ++i){
- output_array.push_back(myheap.get_min());
- }
- return output_array;
- }
- int main() {
- int n_list;
- std::cin >> n_list;
- std::vector<int> list;
- int el;
- for (int i = 0; i < n_list; ++i) {
- std::cin >> el;
- list.push_back(el);
- }
- auto output = psevdo_heap_sort(list);
- for (int i = 0; i < n_list; ++i) {
- std::cout << output[i];
- }
- std::cout << '\n';
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement