链式快排(linked quicksort)实现。
保存一个p_small指针,p_small指针指向比pivot小的数。另外一个指针p一直往右移动,p_small指针只有在遇到比pivot小的数的时候才往前移动。当遇到比pivot小的元素时,p_small指针往右移动一位,然后交换p_small指针与指针p指向的节点的值。
tail在调用的时候需为NULL
#include<iostream>
using namespace std;
struct node{
node():next(NULL){}
node(int d,node *n):data(d),next(n){}
int data;
node* next;
};
void swap(node *p,node *q){
int temp=p->data;
p->data=q->data;
q->data=temp;
}
//tail is excluded in the sequence to be sorted
//actual parameter tail is NULL when first called
void quicksort(node *head,node *tail){
if(head==NULL||head->next==tail||head==tail)
return;
node *p=head->next;
node *p_small=head;
int temp;
while(p!=tail){
if(p->data<head->data){
p_small=p_small->next;
if(p!=p_small)
swap(p,p_small);
}
p=p->next;
}
if(p_small!=head){
swap(p_small,head);
quicksort(head,p_small);
}
quicksort(p_small->next,tail);
};
void printList(node *head){
while(head!=NULL){
cout<<head->data<<" ";
head=head->next;
}
}
int main(){
node n1(5,NULL);
node n2(4,NULL);
node n3(3,NULL);
node n4(2,NULL);
node n5(1,NULL);
n1.next=&n2;
n2.next=&n3;
n3.next=&n4;
n4.next=&n5;
quicksort(&n1,NULL);
printList(&n1);
}