带有双链表的随机QuickSort

我正在尝试实现随机快速排序算法以处理双链表,但我做错了什么。由于某种原因,randomizedQuickSortList()会回忆自己32369次,然后在randomizedPartitionList()的第一行出现分段错误,无论如何(我什至试图编写一个简单的printf()) 。在调试器中运行它,我注意到在某个点之后,pr(在randomizedPartitionList()中)的值始终分别为1和2。

我确信所有其他功能都可以正常工作,并且我认为randomizedPartitionList()函数也可以正常工作,因为我已经将其与其他算法结合使用

int randomizedPartitionList(node** head,int p,int r){
    int s = rand() % (r-p) + p;
    swapNodes(head,findNode(head,s),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,i),j));
        }
    swapNodes(head,i+1),j));
    return (i+1);
}

void randomizedQuickSortList(node** head,int r){
    if(p<r){
        int q = randomizedPartitionList(head,p,r);
        randomizedQuickSortList(head,q);
        randomizedQuickSortList(head,q,r);
    }
}
chenglong676 回答:带有双链表的随机QuickSort

代码是Lomuto分区方案的一种变体,应将索引返回到现在已排序的数据透视元素,然后将其排除在递归调用中(否则可能会发生堆栈溢出,这似乎是该问题): / p>

        randomizedQuickSortList(head,p,q-1);
        randomizedQuickSortList(head,q+1,r);

不包含findnode和swapnodes的代码。我假设findnode通过索引找到一个节点。


由于i和j都按顺序递增,因此可以在分区循环中加速代码:

int randomizedPartitionList(node** head,int p,int r){
    int s = rand() % (r-p) + p;
    swapNodes(head,findNode(head,s),r)); //the indices of the findNode() function start from 1
    int x = (*findNode(head,r))->key; //the findNode() function returns a variable of type node**
    int i = p-1;
    int j;
    node* inode = *findNode(head,p);
    node* jnode = inode;
    for(j=p; j<r; j++){
        if((jnode->key <= x){
            i++;
            swapNodes(head,inode,jnode);
            inode = nextNode(inode);   // new function
        }
        jnode = nextNode(jnode);       // new function
    }
    swapNodes(head,jnode);
    return (i+1);
}
本文链接:https://www.f2er.com/2967682.html

大家都在问