سؤال

I'm wondering what's wrong with my heap sorting code? I just did what's common;read an array,called heapify,deleted the root for each node and printed it. but it didn't work.

void heapsort(int *a,int n)
{
    for(int i=1;i<=n;i++)
    {

        cout << "Enter a["<<i<<"] :";
        cin >> a[i];
    }

    system("cls");

    for(int i=n/2;i>0;i--)
    {
        heapify(i,a,n);
    }

    for(int i=1;i<n;i++)
    {
        cout << deleteheap(a,n);
    }
}


void heapify(int i,int *a,int n)
{
    int l=2*i,r=2*i+1,largest,temp;
    if(l<=n && r<=n)
    {

        largest=l;
        if(a[r]>a[l])
        {
            largest=r;
        }
        if(a[i]<largest)
        {

            temp=a[i];
            a[i]=a[largest];
            a[largest]=temp;

        }

        heapify(largest,a,n);

    }
}


int deleteheap(int *a,int n)
{

    int i=0,x=a[1],k=a[n];n--;
    for(int j=2 , i=1;j<=n;)
    {

        if(j<n)
        {
            if(a[j]<a[j+1])
                j++;
        }
        if(k>=a[j])
            break;
        a[i]=a[j];
        i=j;
        j*=2;

    }

    a[i]=k;
    return x;
 }
هل كانت مفيدة؟

المحلول

I don't have the rep to comment, but i think the mistake is in heapify():

if(a[i]<largest)
{

should be:

if(a[i]<a[largest])
{

as others commented, please explain in more detail what doesn't work according to you next time you ask a question.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top