我正在阅读关于Quicksort的内容,我发现的大多数代码都非常复杂。所以,我决定自己创建一个,其中我将第一个元素视为pivot,然后在列表的其余部分递归调用sort函数。 我为Quicksort制作了以下代码。它如下:
#include <iostream>
using namespace std;
class node
{
public:
int data;
node * next;
};
node * newnode (int x);
void quicksort(node ** begin, node ** end);
int main (void)
{
int foo,n,i,j,k;
node * temp;
node * head = NULL;
node * tail = NULL;
cout<<"How many nodes do you want to insert\n";
cin>>n;
cout<<"Enter data of linked list\n";
for ( i = 0; i < n; i++ )
{
cin>>foo;
node * bar;
if (head == NULL)
{
head = newnode(foo);
tail = head;
}
else
{
bar = newnode(foo);
tail->next = bar;
tail = bar;
}
}
cout<<"The linkedlist that you entered is as follows\n"; // Taking input
temp = head;
node * prev = NULL;
while (temp != NULL)
{
cout<<temp->data<<"\t";
prev = temp;
temp = temp->next;
}
cout<<"\n";
cout<<"Sorting the linked list now\n"; // Calling sort function
quicksort(&head,&prev);
temp = head;
while (temp != NULL) // Printing output
{
cout<<temp->data<<"\t";
temp = temp->next;
}
return 0;
}
node * newnode (int x) // for allocating a new node
{
node * foo = new node;
foo->data = x;
foo->next = NULL;
return foo;
}
void quicksort(node ** begin, node ** end) // actual sort function
{
if (*begin == *end)
return;
node * pivot = *begin;
node * temp = *begin;
temp = temp->next; // for pointing to next element
while (temp != *end)
{
if (temp->data < pivot->data)
{
node * temp1 = *begin; // swapping the two nodes if less than pivot
*begin = temp;
temp = temp->next;
(*begin)->next = temp1;
}
else
temp = temp->next; else moving to next
}
quicksort(begin,&pivot); // calling for remaining elements (first half)
quicksort(&(pivot->next),end); for second half
}
然而,当我运行它时,输入为5 4 3 2 1
,它会进入一个无限循环。我尝试通过调试器运行它,但是在我之间迷失方向的情况下它变得非常复杂。你能指出我可能出错的错误吗?谢谢!