1. 程式人生 > >C++排序(6)——堆排序

C++排序(6)——堆排序

#include <iostream>
#include <vector>
using namespace std;

void swap (int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

void Heap_Insert(vector <int> &num_s, int num)
{
    int Far = (num - 1) / 2;
    while (num_s[Far] < num_s[num])
    {
        swap(num_s[Far], num_s[num]);
        num = Far;
        Far = (Far - 1) / 2;
    }
}

void Heap_Ify(vector <int> &num_s, int Heap_num, int Heap_size)
{
    int Left = 2 * Heap_num + 1;
    while (Left < Heap_size)
    {
        int largest = (Left + 1 < Heap_size && num_s[Left + 1] > num_s[Left])? Left + 1 : Left;
        if (num_s[Heap_num] > num_s[largest])
            break;
        swap(num_s[Heap_num], num_s[largest]);
        Heap_num = largest;
        Left = 2 * Heap_num + 1;    
    }
}

void Heap_Sort(vector <int> &num_s)
{
    if(num_s.size() < 1)
        return ;
    //建立大根堆
    for(int i = 0; i < num_s.size(); i++)
        Heap_Insert(num_s, i);

    //最大值交換
    int Heap_size = num_s.size();
    while(Heap_size > 0)
    {
        swap(num_s[0], num_s[--Heap_size]);
        //調整大根堆
        Heap_Ify(num_s, 0, Heap_size);
    }
    
}

int main()
{
    int num;
    vector <int> num_s;

    while(cin >> num)
        num_s.push_back(num);
    cout << "the original data is: " << endl;
    for (int i = 0; i < num_s.size(); i++)
        cout << num_s[i] << ' ';
    
    Heap_Sort(num_s);
    
    cout << endl << "the Heap_Sort data is" << endl;
    for(int i = 0; i < num_s.size(); i++)
        cout << num_s[i] << ' ';
    system("pause");
    return 0;
}