-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sorting-Quicksort_in_Doublylinklist.cpp
128 lines (126 loc) · 2.6 KB
/
Sorting-Quicksort_in_Doublylinklist.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/*
********************
Q2.
********************
*/
#include<iostream>
using namespace std;
//defintion of structure node
struct node
{
int data;
node *next,*prev;
};
//decleration of functions
void quicksort(node *head,node *end);
node* partition(node *head,node *end);
void swap(int *p,int* q);
void insertion_at_end(node **head,node **tail,int data);
void display(node *p);
int main()
{
int data,choice,pos;
node *head=NULL,*end=NULL;
while(1)
{
cout<<"\nEnter your choice"
<<"\n1.Insertion at end of list"
<<"\n2.Display list"
<<"\n3.Sort the List using Quick sort technique"
<<"\n4.Exit::::";
cin>>choice;
switch(choice)
{
case 1:cout<<"\nEnter the data to insert:";
cin>>data;
insertion_at_end(&head,&end,data);
break;
case 2:display(head);
break;
case 3:quicksort(head,end);
cout<<"\nList After Quick Sort:::";
display(head);
break;
case 4:exit(0);
default:cout<<"\nInvalid input";
}
}
return 0;
}
//recursive function for quick sort
void quicksort(node *head,node *end)
{
if(head!=NULL && head!=end && head->next !=end)
{
node* q;
q=partition(head,end);
quicksort(head,q->prev);
quicksort(q->next,end);
}
}
//function for partitioning the list
node* partition(node *head,node *end)
{
int pivot=end->data;
node *q,*temp=NULL;
q=head;
temp=head;
while(temp!=end)
{
if(head->data<=pivot)
{
q=q->next;
}
else if((temp->data)<=pivot)
{
swap(&(temp->data),&(q->data));
q=q->next;
}
temp=temp->next;
}
swap(&(q->data),&(end->data));
return q;
}
//swap the data of two nodes
void swap(int * p,int * q)
{
int temp;
temp=*p;
*p=*q;
*q=temp;
}
//insertion at the end of list
//here head and end are passed by reference
void insertion_at_end(node **head,node **tail,int data)
{
node *ptr=NULL;
ptr=new node;
ptr->data=data;
if(*head==NULL)
{
ptr->prev=ptr->next=NULL;
*head=(*tail)=ptr;
}
else
{
(*tail)->next=ptr;
ptr->prev=*tail;
ptr->next=NULL;
*tail=ptr;
}
}
//Display the list
void display(node *p)
{
cout<<"\nList is::";
if(p==NULL)
{
cout<<"\nList is Empty";
return;
}
while(p!=NULL)
{
cout<<" -> "<<p->data;
p=p->next;
}
}