【发布时间】:2020-02-29 15:45:03
【问题描述】:
我使用了过去用于数组的算法。这总是选择第一个元素作为枢轴。代码如下:
void quickSort(int a[],int l,int r,int *count)
{
if(l<r-1)
{
*count=*count+r-l-1;
int q=partition(a,l,r); //finding the pivot position in sorted array
quickSort(a,l,q-1,count); //recursive calling before pivot sub array
quickSort(a,q+1,r,count); //recursive calling after pivot sub array
}
}
//partition function definition
int partition(int a[],int l,int r)
{
int j,temp,i=l+1;
for(j=l+1;j<r;j++)
{
//swap values if a[j]<=a[r](i.e. pivot)
if(a[j]<=a[l])
{
temp=a[j];
a[j]=a[i];
a[i]=temp;
i++;
}
}
//place pivot at its position by swapping
temp=a[i-1];
a[i-1]=a[l];
a[l]=temp;
return i;
}
现在是我尝试将其实现为双向链表的时候。 “head”表示链表的头部
void recQuick(void* head, node* s, node* e, int (*comparator)(void*,void*)) {
//s = (node*) head;
if ( e != NULL && s != e && s != e->next ) { //we want to cycle through the linked list
node* pivot = (node*) realQuickSorter(head,s,e,(comparator));
recQuick(head,s,pivot->prev, (comparator));
recQuick(head,pivot->next,e, (comparator));
}
//return 1;
}
node* realQuickSorter ( void* head, node* s, node* e, int (*comparator)(void*,void*)) {
char* piv = s->str; //will always be the first element
node* leader = s->next;
//node* ii = s->next;
node* follower = leader;
for ( follower = leader; follower != e ; follower = follower->next ) {
if ( ((comparator)(follower->str,s->str)) == 1 ) { //pivot is bigger, we need to swap
swap(&(follower->str),&(leader->str));
leader = (leader == NULL) ? s : leader->next;
//leader = leader->next;
}
}
swap(&(s->str),&(leader->prev->str));
return leader->prev;
}
swap、bringMeEnd等功能正确
链表版本似乎只在乱序时交换前两个,其余保持不变
【问题讨论】:
-
不回答您的问题,但最好在数组上使用快速排序。如果你有一个链表,那么合并排序可能会更容易更好。
-
@ybungalobill 这根本不是快速排序。
-
@EOF 你介意详细说明一下
-
在快速排序中,您会将当前索引的元素与枢轴进行比较。您根本没有使用枢轴。另外,我建议使用 Hoare 分区,它对大脑的损伤较小。
-
请在问题中添加足够的代码,以便可以编译和测试代码。
标签: c linked-list quicksort