帮小弟我看看这个堆排序代码哪错了

www.MyException.Cn  网友分享于：2013-03-01  浏览：1次

C/C++ code
```#define LEFT(i) (i << 1) + 1
#define RIGHT(i) (i << 1) + 2
#define PARENT(i) i >> i

int heap_size;

void heapify(int a[],int i)
{
int l = LEFT(i);
int r = RIGHT(i);
int largest;
if (l < heap_size && a[l] > a[i])
largest = l;
else
largest = i;
if (r < heap_size && a[r] > a[largest])
largest = r;
if (largest != i)
{
l = a[largest];
a[largest] = a[i];
a[i] = l;
heapify(a,largest);
}
}

void build_heap(int a[])
{
heap_size = sizeof(a)/sizeof(int);
for (int i = heap_size / 2;i >= 0;--i)
heapify(a,i);
}

void heapsort(int a[])
{
build_heap(a);
int t;
for (int i = sizeof(a)/sizeof(int) - 1;i >= 1;--i)
{
t = a[1];
a[1] = a[i];
a[i] = t;
--heap_size;
heapify(a,1);
}
}
```

------解决方案--------------------

C/C++ code
```
#include <iostream>

using namespace std;

#define LEFT(i) ((((i+1) << 1)) - 1)
#define RIGHT(i) (((i+1) << 1))
#define PARENT(i) (((i+1) >> 1) - 1)

int heap_size;

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

void MaxHeapify(int a[],int i)
{
int l = LEFT(i);
int r = RIGHT(i);
int largest = i;
if (l < heap_size && a[l] > a[i])
largest = l;
if (r < heap_size && a[r] > a[largest])
largest = r;
if (largest != i)
{
Exchange(a[i],a[largest]);
MaxHeapify(a,largest);
}
}

void BuildMaxHeap(int a[],int n)
{
//heap_size = sizeof(a)/sizeof(int);
heap_size = n;
for (int i = heap_size / 2;i >= 0;i--)
MaxHeapify(a,i);
}

void HeapSort(int a[],int n)
{
BuildMaxHeap(a,n);
for (int i = heap_size - 1; i >= 1; i--)
{
Exchange(a[0],a[i]);
--heap_size;
MaxHeapify(a,0);
}
}
int main()
{

int a[5]={5,4,3,2,1}t```