急!!!堆排序问题!!!能排正确一部分数据,还有一些数据不正确
#include <conio.h>
#include <stdio.h>
#include <iostream.h>
int PARENT(int i)
{
return i/2;
}
int LEFT(int i)
{
return 2*i;
}
int RIGHT(int i)
{
return 2*i+1;
}
void MAX_HEAPIFY(int *A,int i,int heap_size) //调整堆节点
{
int largest=i;
int temp;
int l=LEFT(i);
int r=RIGHT(i);
if(i<=heap_size&&A[l]>A[i])
largest=l;
if(i<=heap_size&&A[r]>A[i])
largest=r;
if(largest!=i)
{
temp=A[i];
A[i]=A[largest];
A[largest]=temp;
MAX_HEAPIFY(A,largest,heap_size);
}
}
void BUILD_MAX_HEAP(int *A,int heap_size) //建堆
{
int i;
for(i=heap_size/2;i>=1;i--)
MAX_HEAPIFY(A,i,heap_size);
}
void HEAPSORT(int *A,int heap_size) //堆排序
{
int i;
BUILD_MAX_HEAP(A,heap_size);
int temp;
for(i=heap_size;i>=1;i--)
{
temp=A[1];
A[1]=A[i];
A[i]=temp;
MAX_HEAPIFY(A,1,heap_size-1);
}
}
int main()
{
int a[100];
int size;
while(scanf("%d",&size)==1&&size>0)
{
int i;
for(i=1;i<=size;i++)
cin>>a[i];
HEAPSORT(a,size-1);
for(i=1;i<=size;i++)
cout<<a[i]<<" ";
cout<<endl;
}
return 0;
}
[解决办法]
#include <iostream>using namespace std;int PARENT(int i) { return i / 2;}int LEFT(int i) { return 2 * i;}int RIGHT(int i) { return 2 * i + 1;}void MAX_HEAPIFY(int *A, int i, int heap_size) //调整堆节点 { int largest = i; int temp; int l = LEFT(i); int r = RIGHT(i);[color=#FF0000] /* * 注意这里对堆进行调整时,是从当前节点i,左儿子节点l,右儿子节点r,这三个节点中挑出一个最大的。 * 另外需要注意,l和r的范围不能超过heap_size * */[/color] if (l <= heap_size && A[l] > A[i] && (r > heap_size || A[l] > A[r])) largest = l; if (r <= heap_size && A[r] > A[i] && A[r] > A[l]) largest = r; if (largest != i) { temp = A[i]; A[i] = A[largest]; A[largest] = temp; MAX_HEAPIFY(A, largest, heap_size); }}void BUILD_MAX_HEAP(int *A, int heap_size) //建堆 { int i; for (i = heap_size / 2; i >= 1; i--) MAX_HEAPIFY(A, i, heap_size);}void HEAPSORT(int *A, int heap_size) //堆排序 { int i; BUILD_MAX_HEAP(A, heap_size); int temp; for (i = heap_size; i >= 1; i--) { temp = A[1]; A[1] = A[i]; A[i] = temp; MAX_HEAPIFY(A, 1, i - 1);[color=#FF0000]/* 注意这里堆的大小是 i,而不是 heap_size - 1 */[/color] }}int main() { int a[100]; int size; while (cin >> size && size > 0) { int i; for (i = 1; i <= size; i++) cin >> a[i]; HEAPSORT(a, size); for (i = 1; i <= size; i++) cout << a[i] << " "; cout << endl; } return 0;}