【发布时间】:2015-01-20 03:05:27
【问题描述】:
我最终尝试使用 heapsort 按字母顺序对已读入的单词进行排序。我以前从未做过 heaps,所以我试图跟随我的书。我正在使用 cin 将单词存储到动态分配的数组中,因为单词的数量提前是未知的。从单独的代码中,我知道它正在被读入并且数组正在正确地变大。然后我试图堆化这个数组,但是由于我是编程新手,所以我一直遇到分段错误,我无法确定如何将其追溯到我做错的事情。这是我的 heapify 代码:
void Heap::make(){
//make a heap from wordArray
//r = last non-leaf
for(int r = size/2; r > 1; r--){
int c = 2 * r; //location of left child
while(r <= size){ //size is a data member of Heap
//if r has 2 children and right is larger, make c the right child
if((c < size) && (wordArray[c] < wordArray[c+1])){
c++;
}
//fix if parent failed heap-order condition
if(wordArray[r] < wordArray[c]){
swap(wordArray[r], wordArray[c]);
r = c; //check that it didn't get messed up at c
c = 2 * c;
}
else{
break; //heap-order condition holds so stop
}
}
}
}
通过玩 couts,我可以确定该程序在 if(wordArray[r] < wordArray[c]) 部分之前一直有效。 wordArray 的元素是stings,比较器在外部测试中正常工作。这与动态数组有关吗?我对我在这里做错了什么感到困惑。
【问题讨论】:
-
你有没有试过调试代码找到问题的根源?
-
不知道您的数据类型、数组最大值等。如果 r==size 则 c ==2*size 大于 size。然后 wordarray[c] 是未定义的。
-
我的猜测是你读到了数组的末尾。第一次点击 wordArray[c],c=2*r = 2*size/2,所以你可能正在读取 wordArray[size],但由于它是零索引,这已经结束了。
-
你们搞定了,我的索引与“位置”混淆了。我从这本书中混淆了,因为它从一棵二叉树中显示它的大小为 1,而数组索引必须从 0 到 size-1/我只需要从变量中取 -1 就可以了。谢谢!
标签: c++ arrays algorithm heap heapsort