Graphs and Sorting
SYLLABUS
Graphs: Graph Implementation Methods, Graph Traversal Methods.
Serting: Quick Sort, Heep Sort, External Sorting — Medel for External Sorting, Merge Sort.
LEARNING OBJECTIVES
Graph and its Types
Bosic Terminology Related to Graphs
Vorious Operations Performed on Graphs
Various Types of Graph Traversal Methods .
Quick Sort Technique
Heap Sorting Technique *
Process of External Sorting
External Sorting Mode!
SOR RURAL AES
Merge Sort and its Algorithm.
INTRODUCTION
es) and set of ares (edges). Every
V, E) where, V
‘A graph is @ data structure that consists of set of nodes (ver
edge present in the graph is indicated by a pair of vertices. Itis defined as G
‘a the set of elements called nodes or vertices or points. And Eis the set of edges of the graph
identined with a unique pair (U, V.) of nodes. The various operations that can be performed
‘on graphs are Insertion, Deletion, Traversing and Merging.
Sorting is 0 technique of organizing the data or arranging the records either in ascending or
descending order (Le, bringing soe orderliness In the data), Sorting can be performed on
any one or combination of ene or more aitributes present in ‘each record. It is very easy and
efficient to perform searching, if data Is stored in sorted order It's classified into internal and
‘external sorting, Heap sort fs also known as selection sort algorithm which is on internal sorting
technique, And Merge sort is an external sorting techniqve which makes use of secondary,
storage.
SPECTRUM ALL-IN-ONE JOURNAL FOR EN' IEERING STUDENTS420 DATA STRUCTURES [JNT| 'U-HYDERABAD)
'Q2. Define graph. DI
juss thé differant types
of graphs. ;
oR
What is Graph? Define degree of vertox,
Doc.-19(R 18), a1()
Q1. Explain in detail about graph ADT. Answer =
Answer: Graph
Graph ADT 'A graph is defined as G = (V. E) where,
‘A craph is @ data structure that consists of set | (i) is the set of elements called nodes or vertices
or points.
of nodes (vertices) and set of ares (edges). Every edge
present in the graph is indicated by a pair of vertices.
‘The various graph ADT operations are as follows,
ages of the graph identified with
V) of nodes.
cotes that there is an edge
Eis the set of €
‘a unique pair (U,
Here (U,, ¥) pair den
1. Create(): This method is used to create an empty
Guph The created graph does not contain any | fromnode Ute node
vertices and edges. Different Types of Graphs ,
aes eneatteaph, vel): This method is used | (a) Directed Graph: A directed ‘graph is a graph in
to insert 2 new vertex vel into the graph. The eve the pair of vertices that make up an edge
inserted vertex does not contain’any adjacent wre ordered, In such graph, the order of vertices
edges. representing an edge is important.
3. DeleteVertex(graph, vel): This method is used _ Example
to delete an existing vertex vel from the graph.
‘All the adjacent edges that are connected with @ ©)
vertex vel are also being deleted.
4. InsertEdge(graph, ve2, ve3): This method
incerts an edge e! between the vertices ve2 and
ve3
5, DeleteEdge(graph, ve2, ve3): This method @) (c)
deletes an edge e] existing between the vertices
vve2 and ve3. Figure: Directed Graph
6 Boolean IsEmpty(graph): This method checks , Here, (4, B) and (B, A) represents two distinc
whether the graph is empty or not. If empty, edges.
returns true, otherwise returns false. (>) Undirected Graph: In an undirected graph, the
7, List Adjacent(graph, vel): This method returns order of pair of vertices is not important.
ail the respective edges that are adjacent to the
ster ©)
‘The program for implementing graph ADT is as
follows,
class GraphADT
{
public: . @) (c)
a ‘GraphADT() Figure: Undirected Graph
Here (4, B) and (B, A) represent the same edge
(© Mixed Graph: A graph in which some edges ®™
‘WARNING: Xerox/Pht
3
bool isEmpty( ) Const {return vertices = 0};
int NumberOfVertices() Const {return vertices};
int NumberOfEdges( ) Const {return edge}
virtual int Degree (int p) Const = 0;
virtual bool existEdge (int p, int q) Const =
virtual void insert Vertex (int q)
virtual void insertEdge (int p, intq)
virtual void deleteVertex (int q) = 0;
virtual void deleteEdge (int p, int )
private:
int vertices;
int edges;
jotocopying of this book is.
‘directed and some edges are undirected is know?
asa mixed graph.
Examplewitea: Graphs and Sorting
Ta(V. £) be a graph and let x € E be a directed
associated with thé pair of nodes (U,V). The edge
ie eid to be initiating or originating in node U and
‘eeminating ‘or ending in node V. The nodes Uand V are
tem alled initial node and terminal nodes of edge
ose an edge of @ graph which connects t
called a loop.
(y~ loop
Example
edge x
Inthe above graph, for the edge x, 4 is the initial
node and B is the terminating node.
Degree of Vertex
Degree of vertex (v’) in Graph G is defined as the
number of edges incident on vertex v, self-loop counts
two edges.
Consider an example,
S_@Q_*
elf is
Figure
In the above figure, Degree of vertex v, is 4
Degree of vertex v, is 3.
Explain about connected and no:
connected graph and list the differences
between them.
Answer :
Connected and Non-connected Graphs
Ina graph, ifthere exist a path between every pair,
of vertices then the graph is known as connected graph.
Inaconnected graph, it is possible to traverse from one
node to another node. On the other hand, ifno path exist
between any pair of vertices then the graph is known as
non-connected graph.
Example
Q3.
SPECTROM ALL-IN-ONE JOU!
IRNAL FOR ENGINEERING STUDENTS
il
The graph is connected because thete
from each vertex to every other vertex.
Path A to B:A +> B
AtoC:A+B DC.
AtoD:A+~B>D
O—®)
Figure: Non-connected Graph
“The graph is non-connected because there is no path
from A to D, there is no path from C to any other node.
Differences between Connected and Non-connected
Graphs
‘A directed graph is said to be strongly connected
if there exist a path from every vertex to every other
vertex. On the other hand, a directed graph is said to be
weakly connected if two or more vertices in the graph
are not connected.
‘An undirected graph is called a connected graph if
every node in the graph can be reached from any other node.
Graphically, a connected undirected graph consist of single
‘connected component which is a connected sub graph.
Q4. Write short notes on the following graph
terminology,
(a) Subgraph —(b) Path
(c) Tree (d) Cycle
(e) Parallel edges (f). Complete graph
(g) Cyclic and Acyclic graph.
Answer :
(@) Subgraph
Consider two graphs G and G,, say G, is
subgraph of G if,
(@ All the vertices and all the edges of G, are in G.
(i) Each edge of G, has the same end vertices in G
as in G,.
A subgraph is a graph which is a part of another
graph.
vy
<<). IN\
ve
ee,
Figure
Itcan be observed that, all the vertices and edges
of graph G, are in graph G and also that every edge in
G, has the same end vertices in G as in G,. So, it can be
concluded that G, is a subgraph of G.112
DATA STRUCTURES. [UNTU-HYDERABAD)
() Path
A path can be defined as a trail in which no vertex
appears more than once. In other words ifall the vertices
ina trail are distinct, then the trail is called a path. If in
an open walk no edge appears more than once, then the
walk is called a trail.
(©) Tree
A tree is defined as a finite set of one or more
‘elements with one element designated as root and the other
elements (if exists) are divided into trees are called subtrees.
Figure belowillustrates some ofthe examples of tres.
Q
®
Q oO
, @ ©—O
oO ©
©O—®
©
Figure: Examples of Trees
@ Cycle .
Itcan be defined as a circuit in which the terminal
vertex does not, appear as an internal vertex and no
+ internal vertex is repeated. A circuit is a closed walk,
where no edge appears more than once.
(©) Parallel Edges
Ifa pair of vertices contains more than one edge
then the edges are called as parallel edges. The graph
will be called as multigraph in such cases.
(© Complete Graph ;
Ifa vertex contains edges to al the vertices froma
it, then the graph is called complete graph.
(@), Cyclic and Acyelic Graph
Ifa path contains edges starting from a vertex
and ending at the same vertex, then this path is called
«as eycle. The greph will be called as cyclic graph. If'a
‘eraph does not contain any eycles, then such graph will
be called as acyclic graph.
5. Write short notes on the following repre-
sentations,
(a) Adjacency matrix
(b) Adjacency list
(c) Adjacency multilists.
OR
How to represent graphs? Explain.
Dec.-19(R18), 08
oR
ive example for adjacency list of a graph.
(RE OR ToplesAmacerigy LD)
Answer ‘AprilMay-23(R18), a1(h)
(a) Adjacency Matrix
‘Anadjacency matrix A = (a,) of graph Gis defined
a graph, “V, is adjacent to y>
Ti case of directed graph “Yi i
means that there isa directed ede from V7, 10 ¥,
Example!
Consider the undirected graph given below,
‘Adjacency matrix is,
1
2 3 4
1fpty' to
A=2 [1 o | 0 i
sfifo}o}3
stati to
Example 2 :
‘Consider the directed graph shown below,
Here a, has 1 when there is an edge from ¥,10,
The adjacency matrix A shows the number of
paths of length J between any pair of vertices (Y, V).
The adjacency matrix 4? shows the number of paths of
length 2 between any pair of vertices.
Example 3
___ Consider the adjacency matrix for the graph given
in example 2.
1203 4
1{o; 1] oT} 0
4=2/o0[ofo] 1
3fa[ofo]1|
4loto/]ito
ofifojo of1fofe
ofofof{i] [ofolol!
Ljofoji 1{oj{ol!
ofofifo] fofofife
1234
1fofofo]1
oe? offi [o
3fofififo
4t1[ofof[1
WARNING:eaves that there is Tone path of length 2 from
ma Hy Hts Ty to Vy Fy to Fyand ¥, to Fy
Ren wqibe veritied from graph of example 2,
ws & represents an adjacency matrix
an generals 4
Remar OF aus ‘of length k present between
ajacency Matrix Representation
aback of At
repent pap of nodes adjaceney matrix,
age n> missed: For mast of the graphs, only few
pe ited in mates, So, it ead fo memory
For example,
waste:
ceney matrix for this graph is
1 4
1
0
0
0 0
0 0
0 0
3
0
1
0
1
afi jo 0
Here the size of matrix is 4 * 4= 16, but only
seauies are filled with 1, Hence, a lot of memory
wased,
() Adjacency List
In adjacency list repres
=(V, B), each vertex of ‘graph is represented by 2°
adjacency list. The adjacency list corresponding to
saree contains all vertices that are adjacent © “vin
| ‘G Inadjacency list: representation, each adjacency list
Feared aca chain soit is called linked adjacency
ist representation.
ry ‘A’ is used such
entation of a graph, G
wa
wi CoP
wa ChE ES
™ CHE WA NOL
Figure: Adjcency List Representation for Graph (G,)
Figure: Directed Graph (6)
wa CELE
wa CoP
wi w+ [pout]
va (+
wi ee
Figure: Adjacency List Repre sntation for Graph (G,)
(©. Adjaceney Multilists
‘Adjaceney multilists are the lists in which nodes
may be shared among multiple lists. In adjacency
multilists, for every edge there is. ‘exactly one node. This
rhode is present on the adjacency lists for the Wo nodes
ineident upon it. Consider the following graph,
In this representation, an a"Tay
‘tat Aff points tothe linked list that jneludes all vertices
‘which a particular vertex (V)isconnected, Each node
in the linked list contains two com , vertex
ed link,
strates linked adjacency
» The following figuresil ;
list representations for directed rand undirected gr=phss
fis,
AY -
ponents i.e.
n
‘The adjacency multlists for this graph are as
follows,
TBR) sven
, aden: 81 5
Grafs] 12 Noes ote
ase: N5
Tali} na Notee na 98
Nisee N84
7]
Tse ss
GraphiG,)
Figure: Undi
RS SPECTRUM ALL-IN-ONE
JOURNAL FOR ENGINEERING STUDENTSYDERABAD}
explall
at DATA STRUCTURES INT
G7. What aro tho various oporations that can
The format of node structure in adjacency
ists is
Link |
Node 1 | Node 2 Link 2 ]
Where node! and node? represents the shared
edge. Link 1 and link 2 represents the next unvisited
edges from node 1 and node 2. For example, nodes for
shared edge NI are a and b, The next unvisited edges
for those nodes are NS and
Q6. Discuss the pros and cons of various
graph representations.
Answer >
Graph Representations
faph representations are as
‘The three common gt
follows,
1. Adjacency Matrices
Pros: The pros. or advantages of adjacency matrices
are as follows,
It is preferred for the graph storage where there
exist less number of edges.»
«+ Itefficiently determines the relations!
ina graph.
Con: For answer refer Unit-1V, Page No. 113, Q5, Topic:
Drawback of Adjacency Matrix Representation.
2, Adjaceney Lists
Pros: The pros or advantages of adjacency lists are as
follows,
‘> It offers a compact representation for sparse
graphs.
4 Ttean be directly used for weighted graphs.
4 Itoffers robustness of adopting various other repre-
sentations.
Cons: The cons or disadvantages of adjacency lists are
as follows, 5
“It does not provide faster ways of determining
whether a specific edge’exist in the graph or not.
‘ _Itiscomplex when compared to adjacency multil-
ists
3. Adjacency Multilists
Pros: The pros or advantages of adjacency multilists are
as follows,”
4 Itallows sharing of nodes within multiple lists.
+ Itoffers simplified representation when compared
_ toadjacency lists.
Con
The main con or disadvantage of adjacency
multilist is that, it does not work well'when the
‘number of vertices are less. ;
bo performed on graphs
Model Papers, €9(b)
Answer :
“The vation mat can be performed are,
\eva
us operations th
1 Insertion
a vertex into the graph fest allocate thes
mory to the ne’ {then store the ut data
rae ew Ver E eia data elements
wrtex, Next, set all the met
in the new vertex. Next, ee
TONULL, While inserting the verte’ chetk whet te
ie ertex must be inserted before
viaph isempty or the new Ve be inserted befor
thelist ‘vertex. In both the cases, the NEW vertex becomes
the first node of the graph, If neither ‘of the ease is true
then insert the new vertex in sequence,
‘To insert a
ww vertex
Algorithm:
a —» data that has t
sory for the new VErleX,
/ERTEX*)malloc(size of VERTEX)
Input: dat be inserted into vertex.
Step1: Allocate met
newvertex=(VI
newvertex,
Step2: Store datal
newvertex — dataptr=data;
Step3: Initialize meta data elements in new vertex,
newvertex — outdegre
newvertex —> indegree=0;
newvertex —> processes
newvertex — pArc=NULL;
newvertex — ptrNextverte
‘Step: graph + count++;
StepSeIf graph is empty,
iffgraph — first
NULL)
Set the first vertex to new vertex,
graph — first=newvertex;
Step6:else
‘Search for the insertion point,
prev=NULL;
while(loc & (graph —> compare(data, loc —+ dataptr)>®))
pres
5 ‘
loc=loc —+ ptrNextvertex;
Insertion vertex before the start node
if(tprev)
graph — start-newvertex;.
else ‘
Insertion of a new vertex in sequence,
pre— ptrNextvertex=newvertex;
newvertex — ptrNextvertex=I
Step7: end
EE a cS SRT Tram
‘wi Tt acer ad eG amie this tava aaNetGraphs arid Sorting
Deletion
To delete a vertex, initially sea
mgr itty er te ee
‘feck whether any are is ehtering (indegree) or leaving
{outdegree) the vertex. A vertex with degree greater
fan zero cannot be deleted. So to handle such a vertex,
a check for indegree and outdegree in the vertex is ree
quired.
Algorithm
Input: Key is the key of the vertex which has to be de-
Ieted from a non empty graph, 7
stept:If graph is empty,
Iffgraph — start =NULL)
return-1;
sstep2:Search for the location where key is present,
prev-NUL
pir=graph—first;
while(ptr &&(graph — compare(key, ptr >
dataptr)>0)),
+ prev=ptr;.
pir=ptr — ptrNextvertex;
‘Step3:If vertex is not found, i
ifttptr | graph > compare(key, ptr — dataptr)!
¢ a
return -1;,
Step4iIf vertex is found, test the degree,
if ptr — indegree > 0 || ptr outdegree0)
return ~2;
“StepS:Delete the vertex,
if(tprev)
graph — first = ptr + ptrNextvertex;
else
prev — ptrNextvertex=ptr — pttNextvertex;
Step6: Decrement the count after deletion, :
graph — count;
Step7:return 1
Step8:end
3. Traversing
For answer refer Unit-IV,
4. Merging
Merging operati
graphs say G1 and G2 int
Page No. 115, Q8.
jon involves merging of two
to a new graphs G3. In addition
tb this, seme of the new entties are present With espa
to new edges. So, merging can be done by copying
adjacent matrices of the components and then setting
new edges with entries.
Algorithi
“Stepl: Initialize the entries of the
fori=1tondo
forj=iton do
DGpitlilfi) = 9
endFor
endFor
matrix of graph.G-
to the adjacent
2
‘Step2:Copy adjacent matrix of G1
matrix of G
fori=1ton, do
for j= 1 ton, do
DGptfilfi) = DGIptLilLT
endFor
endFor
Step3: Copy the adjacent matrix of G2 into the adjacent
matrix of G
for i=1 ton, do
for j= 1 ton, do
DGpt{i +n] + 4,) = DG2prli]ET
endFor
endFor :
Step4:Sct the edges from G1 to G2 doFlag = TRUE
While(doFlag) do
Read(v, w)
If{v
#include ‘Header file section
dinclude
##define MAX 20
typedef struct Queue
{
int data[MAX];
int nh; j
Jqueue;
typedef struct node
‘WARNING: KeroxIPhotocopying of this book iy a CRIMINAL act. Am 1 Number of nodes i
int deque(queue *);
int empty(queue *);
void BFS(int);
void graph(); /iCreate an adjacency list
void insert(int v
¥2);
‘Mnsert an edge (v1,v2)in aK
Yoid DFS(int i
int vis[MAX];
node *G[20};,
eteads of the linked list
int
fie BLE to faco LEGAL procesdi™®™graphs and Sorting
we) Trin tani ius
t ‘void DFSMina fy
ait ‘
eet node *
e Prinele“tad € iy,
t rat;
redial KCrede 2)BFS 3)DFS 4). visi}
~ gSelect your option: Krvie"y, whilelp!=NULL)
option:"y, a
Feed Lech, t
gwachich) npovertex;
{ ifttvis{ify
—— DSU
bee: peponent;
a ;
case T: pref" Enter the starting node number“) 5
sealed Ki, aa :
BES}. ‘void enque(queve *e,int x)
Minar elements into the queve
ban . i
case 3: fortran) iffeon—=1)
oooh
e-mdatafern
4
else
{
concent;
edataleon]=x;
;
t ;
ice wivislMAAL int deque(queue *c)
queue g; ‘Delete elements from the queue
quese G "
rede *p; {
int x
garqhat; n me
feniitrinii*) are ttalo
ee if e>n—=c->h)
equa),
prin Md 0);
visfv}=1;
whildtenpty(Zq))
t cehec-rhtl;
wodequcdéeay; return(x);
forlp-G{v]p!“NULL sp P79 }
‘Menara urvisited abjaces vertices Of vio que void graph()
t (
wep vertex; int il v2,¢;
ittvisfu==0) printf(“Enter number of vertices 2")
t seant("%d" den);
for(i=Oii ‘MHleader file section
Void insert(int v1,int v2) int q[20],t=- Lye
{ 1iGlobal declaration of variables
node *p.*q: int A{10][10],B(20},Stk(20];
g=(node *)malloc(sizeof{node)); . 4
Acquire memory for the new node wold éreate(int item}:
ae void BFS(int x,int y);
qonext=NULL: void DFS(int x,int y):
iRGIvI}=NULL) void push_item(int item);
insert the . int pop_itemO;
eect inthe linked list for the vertex.no. VI void main) ‘/imain Function
ce { ao
{ int num,,s,choice;
- char od;
p=Glv i clrser();
while(p-Snex ULL) printf(*Pleas¢ enter the total number ofvertices.")
_ Goro the end of linked list” scanfi"%a”, num);
pep>next; num:i+)
ponext=q; .
; e for(j=1;j<-num;j+)
{
int empty(queue *c) 5 printf(“Press 1 if Yd had a Node with %d else
{ press 0:",ij);
ite>a—1) scanf(“%d",&ALILDs
retum(1); }
return(0); }
} printf(“The Adjaceney Matrix is:\n”);
for(i=l;i<-num;i++)
{
for(j=1;j<-num;j+1)
{
printf %d”,ALGDs
¢
eae ar ac
Gime carats: printf(\n");
Seesmic }
- do
{
ped for(i=:
Peete Bli
roe rae Ro, printf(‘\n MENU: 1.BFS 2.DFS”
artemis e a printf(“\n Select your option:”);
pone scanf(“%d"éechoice);
Se SIN printf(* Select the Sourcé Vertex:
ee au . scanfl“%d",&s);
rms en RT ae ae switch(choice)
a {
case 1:
BFS(s,num);
break;
case 2:
DFS(s,mim);
break;
. 5| Dwit-4:.Graphs and Sorting
f Y to continue else press N>
ca
scante" wo:
while((c
etch);
}
void BFS(int s,int num) //Breath fist search code
{
int x,i,a5
create(s);
Bis}:
xedelete();
iffx!=0)
printf" %d",x);,
while(x!=0)
xedeleteQ;
iffx!=0)
printf(* %d"x);
}
fori
sissnum;i++)
it )
BFS(,num);
}
Void create(int item) _// Create function
iff(—=19)
Print(“Queue isnot empty”);
a
t=
{
gl++1litem;
}
int delete()
Delete function
int ks
i(n\(=1))
)
if((AtKItI D)&R(Bi}=0)
‘ push_item(i); B[iJ=1;
void push_item(int item)
/MEunction to perform push operation
if(t=19)
Stack overflow”);
else
Stk{+}=item;
}
{nt pop_item() //Function to perform pop operation.
{
8122
4.2 SORTING.
4.2.4 Quick Sort!
Q12, Explain in dotail quick sorting method.
Provide a complete analysis of quick sort.
Answe Model Papers, a8(@)
Quick Sort Method
Quick sort technique is based on the divide and
conquer design technique, In this technique at every step
cach element is placed in its proper position, It performs
very well on longer lists. I works recursively, by first
selecting a random “pivot value” from the list (array).
“Then it partitions the list into elements that are fess tha
the pivot and. greater than the pivot: The problem of
sorting a given list is reduced to the problem of sorting,
two sub-lists and process continuous until the list is
sorted. This Sorting technique is considered as in place.
Algorithm for Quick Sort
“This algorithm sortsthesub-array A[fist].ALlast]
of a globally defined array A[0....n] in ascending order,
Algorithm QuickSort(firsty10s0)
Input: Indexes of the elements to be sorted
Allast] is a sorted rearrangement oF
Output : Affirst,
the same elements
if{first pivotl
high «high = 1
ment)
, if\low < high)
swap(Allow}, Afhigh})
return high; wr)
Algorithm swap(a, b)
temp =a
aed
beter
DATA STRUCTURES [JNTU-HYDERABAD)
‘Analysis of Quick Sort
“The quicksort is analyzed based on its woist cas,
est ease and average case.
(Worst-case Analysis: In worstease, the chose,
pivot is either the smallest or the largest element inn
renay. In this ease, ong partis empty and the other par
caniains the remaining clements this generates m~
Jevels in the recursion tree.
When quick sort is first called partition takes ime
-1, Quick sort is then called twice, once with an empty
ray and again with an array of size n~ 1. The next eal
{o partition takes time 1 ~2. Quick sort is again called
twice, once with an empty array and again with an array
of size n—2. Thie next call to partition takes time n-3
nd the process continues, The total time forall the calls
to partition
n(n)
(= I) (= 2) 493) Hae EL if asl)
Gil) Best-case Analysis: Quick sort works best if
each array is divided into two equal sub-arays of siz=
n/2. This generates log n levels in the recursion tree. THe
recursion relation is given by,
Tn) = 2M!2) + OM) +
On applying the master theorem,
Tn) = O(n logn)
(i) _Avernge-case Analysis: In average-case the
array is partitioned by choosing any random number,
In this ease at each level some of the partitions
well balanced while some are fairly unbalanced. Let
us assume that the partition of array to be 9:1 then the
recurrence so obtained is,
+ Ta) = TOn/1O) + Te/0) + Cn
‘The recurrence tree is shown in figure.
ciGiven list
4
12, 35; 23, 45, 34, 20, 48]
I the elements of given sequence in the
sarrangeall
| se ‘ofan array, Therefore array (x)
} el 35 [23 145 [34 [20 [48
| ype Sette fist element as pivot element,
| «pivot = 24
Consider the element next to pivot as i and last
} clement as j.
Therefore, i= 12,7 = 48
Low High
Pele Bs Bs 4s [34 [20 [a8
Pivot i sd
‘1ep3: Since X(i) £ pivot, increment i until the element
point by i is greater than pivot.
High
Te Bs 3 [4s 34 Po [as
Pivot i i
{: As X(i) > pivot we stop incrementing i and X(j)
> pivot decrement j until element X(/) is less than
pivot.
Low High
24 | 12 [35 | 23 | 45 [34 }20 | 48
Pivot i j
As XW) pivot, increment i
until element pointed by A (i) is greater than pivot
and decrement element pointed by A(/)is less than
Pivot. .
[2s [iz Teo [23 Fs [34 [35 148
Pivot i B
Low High”
24 [12 [20 [23 [45 [34 [35 148
Pivot i
24 [a2 [20 [23 [45 [34 135 148
Pivot
(i) = pivot
swap pivot a
ul j has crossed {he
~
23 [12 [20 [os
; 3 [12 [20 Daa a5 Baa as Taw
Step8: As pivot is placed at its position partition the
above list into two sublists,
23 [12 [20 [24 [a5 [94 [as [aa
i Pivot 1
‘Step9: Consider the first sublist S1,
Low _" High
23] 1220
Pivot bj
Since A() < pivot increment / and j. :
23] 12]20
Pivot i,j °
23] 1220] . .
Pivot ji ‘
Step10: Since A() < pivot and / erossed i, swap AQ)
and pivot,
12 [ 23 | 20 |
a Foe
S, Pivot S,
Stepll
oo J
12 | 23 | 20
Pivot. i,j 7
Since j cannot be decremented more-and as X(/)
pivot stop increnfenting. Now
mpare X(i) with pivot since X(/) > pivot
decrement j
45 | 34 135 | 48
Pivot J i
Step14: Since A{j) < pivot and since / crossed j swap
XG) and pivot.
35 [34] 45] 48
Pivot
Ss, s,
Step15: Since pivots placedatits position divide the above
listinto two sublists and then perform sorting. This.
can be represented as follows,
“st wid
as [34 [45] 48
: Pivot hi
oer Ar A(j) < pivot swap A(/) and Pivot. Hence
4 is,
3435] 45 | 48
Since the list is already sorted swapping cannot
be performed further. Thus the sorted list is as follows,
12 [20 [23 [24 [34 [3s [45 [a8
Justification for “Quick Sort is not a Stable Sorting
Method”
‘8 show that quick sort is not a stable sorting
algorithm, let ky ky, Ay :.k, ,bea sequence of numbers,
A sorting algorithm is stabie if for any two numbers &
and k, such that k, = k, and k, precedes &, before sorting
(ic., 15). Then k,also proceeds k, after sorting. Quick
sort ‘a stable sorting method because the relative
order of two equal numbers after sortirig is not same as
they were before sort
Q13. Apply quick sort to sort thedist E, x, A,
M,P, L, E in alphabotical order. Draw the
tree of recursive calls made.
Answer =
sider the given list in the form of an
aia, afffownteon el
DATA STRUCTURES [INTU-AYDERABAD)
Consider the first element ‘E’ as the pivoupy
element ic. a (0] = PvtG.e. pivot), and, st the poinan
iand jas follows,
Dt 2 38 4 SG
e)x}alm|ede =|
pei i
Now, perform quick sort on the above array tg
obtain an alphabetically ordered list.
Step1:Since, a [i] > pvt(i.e...X > £), iis not incrementeg,
However, as a [j] 2 pvt(ic., £2 £),,J is decre.
mented as shown below,
o 1 2 3 4 5'6
e|xfalmM|]Pp]ele
pti j
Step2:Since, a [/]
again. 7
o 1 2,3 4 5 6
Pat i
‘Step4: Since, a [/] > pvt (i.c., M> E), is decremented
o 1 2 3:4 5 6
Ee] x]almM/rp]ocle
mm iG
StepS:Since, af/] < pvt(i.e., A pvt (i.
X> B), therefore, iand/ are not moved. Butthey
are exchanged (or swapped) as follows,
or 23 4 5 6
Elalxiu| el] e
mT
Step6:Since, a [i] pvilies
X> E), iand jare incremented and decremen
ee ee ee
Eyalx|[mMieplde4, Grophs.and Sorting
cre in no alphabet that comes before
vai said to be in correct position, Since E
os ater 1A" ftom the given elements, "Eis
boat ‘aid to be in correct position. Hence, leav-
r a these two elements, comsider the remaining
| hements, a8 right sublist
| erect position
Right tublist
der the right sublist and set the first
clement as the pivot element. And also set the /
and pointers as follows,
o 1 2 3 4 5 6
react
Thtelx|udelele
Lodo 2
Mi i
Step$:Since, afi] < pvt, lis incremented. This is contin-
ved until the condition is satisfied.
o 1 2 3 4 5 6
Gee
tarerx[ um] etofe
L---- 411
“Pat i
epl0: Since, aff] and aff] are less than pivot element.
Therefore, the pivot element and the element at
Zand j are exchanged as shown below,
Cones poston
0 f. 6
totes
— asa
‘atelefulel ol x}
Lode 23
OT
Len vb
As there is no alphabet in the array that comes
after X; hence it is said to be in correct position.
‘And consider the remaining element as left sub-
list
‘PII: Consider the left sublist and set the first element
as, the pivot element. And also set the i and j
Pointers as follows,
oy Jo 3 4
125.
Stepl2: Since, Ai]> pili, M> B),sisnot incremented.
But, as aff] > priie., L > B)j is decremented.
o 1 203
Step13: _ P> E), jis decremented.
‘This is continued until the condition is satisfied.
Low High
ska sh
a |p | L
=
Right sublist
Since, j= pvt and there is no elements that comes
before E. Therefore, E is said to be in correct
position. Whereas, the remaining elements forms ~
the right sublist.
Step14: Now, consider the right sublist and set the first
element as the pivot element. And also set the i
and j pointers as follows,
22 acs
are
=e
Step15: Since, a{f] > pvt (P > M), iis not incremented.
And aff] < pivot(ic., L < Mf), j is not decre-
mented. But afi] > aff} (i:e., P< L), therefore -
afi] and aff) are swapped.
o 1 2,53 4 55
ei
Step16: Since, afi] > pvt and alj] < pvt, therefore i
and j are not incremented and decremented
respectively. However, pivot element M and
the element at j are swapped, because £ =o,
To transform a ular subtree into a heap,
follow the steps given below,
(i) Suppose that List{/e] and List(re] are the leftana
right children of List{].
(ii) If List[Ic] and List{re] to) find the largest of them.
“The index of largest element is stored in “largest.
If List] is less than Listflargest], swap Lisc{q]
with List[largest]. Otherwise, exit ie., the subtree
is already a heap.
(iv) | If values have been swapped in step (iii) then,
there are chances that the sub-tree Listflarzex]
might have become a non-heap. ‘Therefore, we
apply steps (ii) and ({ii) at that sub-tree until al
the heaps in the sub-tree are restored or until
encounter an empty subtree.
‘After constructing a heap, the next phase is,
sorting heap begins.
Algorithm (Construct Heap)
Step 1: Consider a heap tree which is empty. Begin at
the first step,
i=1
while (i n)do
‘Step 2: Repeat step 2 for all the elements
Step 2.1: Select the i* element from list and add =
‘element to the i* place in array
n=An{i]
Aml[i]=0
i
Step 2.2: Repeatstep 2.2 to step 2.3 until the root is checked
If Ant{j] > Arr] j/2] then
tmp =Arl fj)
Arrl{j] = Ari §/2]
(ii)
End If
Step 2.3: End while
i=i+l
Step 2.4 : End while
Step 3: stop -
Function
a Adjust_maxheap(element any ], int root, it)
int ch, root_key;
element tmp;
tmp = arrfroot];
which is not leaf and has at least one child.
root_key = arrfroot] key:
‘Anyone found guilty is LIABLE ta face LEGAL preczedings|
|
|
4 ora and Sorting
ut
Tye 2? 100!
wwhite(ch <=")
i(ch arr[ch].key)
breaks
else
arsfeh/2] = arr{ch};
ch* =2; .
)
arr{ch/2] = tmp;
Sort Heap
In this phase, the given heap is sorted. Note
that the root node of heap (ic, the first element of the
ist) will be ‘the largest clement in the tree or li
following steps sort the heap,
0
t. The
‘wap the root node (i.e, first element of array list)
with the last node of the tree (ic, last element of
array list). Now, last node is in its proper place.
Leave the last element and consider the remaining,
elements as the new list.
‘The new list may not be in heap form. Therefore,
construct a heap of new list.
Gi
(iv) Repeat steps (i), (i) and (ii) until all elements are
placed at their proper place, ic, until all elements
are sorted.
Algorithm
"Step 1: Read all the elements and store in the array.
‘onstructHeap (Arr)
cepeat this step for n — 1 times
‘Step 3.1 Remove the root element and swap it with the
‘element.
tmp = Arti]
Arrl(i)=Arel[1]
Arcl(1] =tmp
Step 3.2: Pre build the heap
Cannot build heap with on
If (=I) then
exit
Begin at the root node
ye element in the tree
flag = TRUE i
while (flag =TRUE) do
25
right = 24) +41
heck whether
heap and check whell
move up or not.
If (right 05
‘Adjust_maxheap(arr, i n);
forli=n—1;i>0;i--)
{
SWAP(arr{1], arefi + 1], tmp);
Adjust_maxheap(ary, 1, i);
3
3
Example
Consider below list oF elerients,
tbl DP Dee
(ONO CO MO ONO MOMO!
Constructing Heap
“The first step in heap sorting is to construct heap.
For this, consider three pointers i, c, re"where i points
to a particular node and fe, re point to the left and right
child respectively.
Inititly, = S22QE St s Hist
i=s-1=4
Left child,
e=(2x)t1= 2x4 t1=9
Right child,
re=(2x)+2=(2%4)+2=10
Arri (left) 2 Arr [right] then
NE JOURNAL FOR ENGINEERING ‘STUDENTS128
8 [7To Tita
Se
DATA STRUCTURES [JNTU-HYDERABAD}
is in the following list,
[2
0 PY Br wr ist tr ar aa To
i t
le
aa As, there is no right child of i, the Ic is compared
with i. If fe > i, they are swa le they are swapped. Ife i, no swapping
In the next iteration, decrement ‘i’ which makes
i= 3. Now, Ic and re can be calculated as,
i=3
le=(2*3)41=7
re=(2*3)+2=8
é[sl7]°]'[4[3]2]|s5]0
(9) 0) (2) g 4) (5) 1 (7) (8) 19)
ae
‘Now compare the element pointed by /e and re
(ie., 2 and 5) and find the largest among them. Since
5 > 2, itis compared with / (ie.,.9). Since 9 is greater
than 5, the subtree is already a heap, so swapping is not
needed.
In the next iteration, decrement / which makes it
2. Determine /e and re.
sD 14]3]2[s]9] -
4) (5) 16 (7 8) 19)
t t
Now, compare the elements pointed by le and re
(ie., 4 and 3) and find the largest among them. Since 4
>3,4is compared with i(ic., 7). Since 7> 4, the subtree
is already a heap, so swapping is not needed.
In the next iteration, decrement i which makes it
1. Determine fe and re.
i=l
le=(2% 1) +1=3
re=(2*1)+2=4
This implies i= 8, le= 9 and re = 1.
Now, compare /e and re (ie., 9 and 1) and find
the largest among them. Since 9> 1, itis compared with
#* element. Since 8 <9, swap these values i.e, i and le.
6
@ 1 2 By
7T8Ti[4]3]2]5]o
2B 6) 1 & Oy
Note that the swap operation has distributed the
heap in the subtree. So, to restore the heap in that subtree,
initialize the pointer i to Ic. .
i=3
sle=(2%3)+1=7
re=(2.*3)+2=8
é]>171*1' 1413 [215Je
aoa sw 8 6 Mw
uy it
‘Swap the largest element among /c and re with i
if i 5 which means that the subtree
is already heap, so swapping is not needed.
In the next iteration, decrement i which makes it
.. Determine /e and re.
2
(2x2)+1=5
re=(22)+2=6
This implies i= 7, lc=4 and re=3. Now, compare
te and re (i.e., 4 and 3) and compare the largest among
Je and re with i(i.e., 4 with 7). Since i> Ic, the subtree
is already a heap, so swapping is not needed.
‘The process is repeated for i= 1
For i= 1, there will be no change in the positions
of elements. The value of / is decremented again to i=0.
i=0
2*0)+1=041
= (2 0)+2=0+2
Now, compare the elements pointed by fe and re
(ie., 9 and 7) and compare the largest among them with
the value of i. Since 6 <9, the values are swapped.
This results in the following list.
®
> k
> re
Q Q
® O 6 ©
® OO
RIMINAL,
t. Anyone fount