【发布时间】:2020-03-30 18:07:35
【问题描述】:
我正在尝试实现随机快速排序算法来处理双链表,但我做错了。出于某种原因,randomizedQuickSortList() 自我调用了 32369 次,然后我在randomizedPartitionList() 的第一行遇到了分段错误,不管那是什么(我什至尝试写一个简单的printf())。在调试器中运行它,我注意到在某个点之后,p 和 r(在 randomizedPartitionList() 中)的值总是分别为 1 和 2。
我确信所有其他函数都可以正常工作,并且我认为 randomizedPartitionList() 函数也可以完美运行,因为我已经尝试将它与其他算法结合使用
int randomizedPartitionList(node** head, int p, int r){
int s = rand() % (r-p) + p;
swapNodes(head, findNode(head, s), findNode(head, r)); //the indices of the findNode() function start from 1
int x = (*findNode(head, r))->key; //the findNode() function returns a virable of type node**
int i = p-1;
int j;
for(j=p; j<r; j++)
if((*findNode(head, j))->key <= x){
i++;
swapNodes(head, findNode(head, i), findNode(head, j));
}
swapNodes(head, findNode(head, i+1), findNode(head, j));
return (i+1);
}
void randomizedQuickSortList(node** head, int p, int r){
if(p<r){
int q = randomizedPartitionList(head, p, r);
randomizedQuickSortList(head, p, q);
randomizedQuickSortList(head, q, r);
}
}
【问题讨论】:
-
minimal reproducible example 会很有用。我们无法确定其他部分是否正常工作,即使它们似乎在其他地方工作,并且有确切的输入条件来确定在它不工作的情况下发生了什么总是有用的
标签: c list sorting quicksort partitioning