最小堆查询法

来源:互联网 发布:出让股份分配怎么算法 编辑:程序博客网 时间:2024/05/16 10:34

#include "stdafx.h"
#include <iostream>
using namespace std;
void SortSatck(int b[],int n);
//构造最小的
void MakeStack(int a[],int n,int m)
{
    int i,j,temp;
    //将数值加入到最后的位置上
    a[n] = m;
    i = n;
    j = (n-1)/2;
    while(j >= 0&&i!=0)
    {
        if(a[i] < a[j])
        {
            temp = a[j];
            a[j] = a[i];
            a[i] = temp;
            i = j;
            j = (i-1)/2;
        }
        else
        {
            break;
        }
    }
}
void sort(int b[],int n)
{
    if(n == 0)
        return;
    int temp =  b[0];
    b[0] = b[n];
    b[n] = temp;
    SortSatck(b,n-1);

    for(int i=0;i < 10;i++)
    {
        cout<<b[i]<<" ";
    }
    cout<<endl;

    sort(b,n-1);
}
void SortSatck(int b[],int n)
{
    if(n == 0)
        return;
    int i,j,temp;
    i = 0;
    j = i*2+1;
    while(j<n && j> 0)
    {
        if(b[j] > b[j+1])
            j = j+1;
        if(b[i] > b[j])
        {
            temp = b[j];
            b[j] = b[i];
            b[i] = temp;
            i = j;
            j = i*2+1;
        }
        else
        {
            break;
        }
    }
}
int _tmain(int argc, _TCHAR* argv[])
{
    int A[10] = {98,18,69,34,78,27,47,57,52,36};
    int b[10];
    for(int i = 0;i < 10;i++)
    {
        MakeStack(b,i,A[i]);
    }
    for(int i=0;i < 10;i++)
    {
        cout<<b[i]<<" ";
    }
    cout<<endl;
    sort(b,9);
    for(int i=0;i < 10;i++)
    {
        cout<<b[i]<<" ";
    }
    cout<<endl;
    system("pause");
    return 0;
}



原创粉丝点击