struct node
{
int data;
struct node *link;
struct node *plink;
};
struct node *first=NULL, *last=NULL;
void swap(struct node* a,struct node* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void qsort(struct node *low, struct node *high)
{
if(low==NULL || high==NULL || low == high || low->plink == high)
return ;
struct node *pivot=low, *tmp=low->link;
while(tmp != high->link)
{
if(tmp->data < low->data)
{
swap(pivot->link, tmp);
pivot = pivot->link;
}
tmp = tmp->link;
}
swap(low, pivot);
qsort(low, pivot->plink);
qsort(pivot->link, high);
}
Quicksort can be implemented for Linked List only when we can pick a fixed point as pivot. Random QuickSort cannot be efficiently implemented for Linked Lists.
Quick Sort using Double Linked list
struct node
{
int data;
struct node *next;
struct node *prev;
};
void swap(struct node* a,struct node* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void qsort(struct node *low, struct node *high)
{
if(low==NULL || high==NULL || low == high || low->next == high)
return ;
struct node *pivot=low, *tmp=low->next;
while(tmp != high-next)
{
if(tmp->data < low->data)
{
swap(pivot->next, tmp);
pivot = pivot->next;
}
tmp = tmp->next;
}
swap(low, pivot);
qsort(low, pivot->previous);
qsort(pivot->next, high);
}