【发布时间】:2019-05-20 07:41:00
【问题描述】:
我正在尝试使用 heapsort 对类哈希表的对象进行排序
struct hashmap{
int key;
int value; };
vector<hashmap> heap;
int n;
void heapify(int i)
{
int l,r,max=i;
l=2*i+1;
r=2*i+2;
if((heap[r].key>heap[max].key)||((heap[r].key=heap[max].key)&&(heap[r].value>heap[max].value)))
{
max=r;
}
else if((heap[l].key>heap[max].key)||((heap[l].key=heap[max].key)&&(heap[l].value>heap[max].value)))
{
max=l;
}
if(max!=i)
{
swap(heap[max],heap[i]);
heapify(max);
}
}
void heapsort()
{
for (int i=n/2-1;i>=0;i--)
heapify(i);
while(n>0)
{
swap(heap[n-1],heap[0]);
--n;
heapify(0);
}
}
int main()
{
cout<<"Enter the no of elements : ";
cin>>n;
Det(n);
heapsort();
display();
return 0;
}
如果我的输入是 (1,3) (2,5) (1,2) 我的预期输出应该是 (1,2) (1,3) (2,5) 但这不是我的我得到了。我得到了一些随机数作为输出。
【问题讨论】:
-
您能否添加一个
main函数来重现您的问题? -
注意
=和==之间的区别。 -
您的变量
n已初始化,但您没有给它任何值,这意味着它具有随机值。然后你在heapsort上做所有的循环。这对我来说听起来有点奇怪 -
@DrosvarG 全局变量默认初始化为
0。这正是问题所在。heapsort对n == 0没有任何作用。 -
if内部的这个任务是故意的吗?(heap[r].key = heap[max].key)
标签: c++ recursion vector hashmap heapsort