7/30/2019 Lec7(Quick Sort)
1/12
CSC341
/ISC361
CSC341
/ISC361
CSC341
/ISC361
CSC341
/ISC361
DataStru
ctures&Algorithm
s
DataStru
ctures&Algorithm
s
DataStru
ctures&Algorithm
s
DataStru
ctures&Algorithm
s
SORTING-QUICKSORT
QuickSort
-S
aceCom
lexit
8/22/2009 Sundar B.
CallStacksand
FunctionCallOverhead
-Recursive
Functions
-TailCa
llsandTailRecursion
QuickSort
-Function
CallOverhead
-TailCallElimination
-UseofExplicitStack
-ControllingStackSize
1
CSIS, BITS, Pilani
7/30/2019 Lec7(Quick Sort)
2/12
QUICKSOR
TSPACECOM
PLEXITY
QuickSort
usesadditionals
pace
throughtherecursivecalls
forkeepingtrackofallthesub-liststhataretobesorted
Worstcas
e:Unbalancedpa
rtitioning
Exactly
N-1
framesoncalls
tack(atmaximumd
epth)
8/22/2009 Sundar B.
Averagec
ase:Balancedpartitioning(constantfactorbalance)
(logN
)framesoncallstac
k.
Bestcase:Equalpartitions
Exactly
logNframesoncall
stack(atmaximumdepth)
Isthisopt
imal?
Canwe
reducethecallstac
koverhead?
StackSize
Fram
eSize
2CSIS, BITS, Pilani
7/30/2019 Lec7(Quick Sort)
3/12
CALLSTACK
8/22/2009 Sundar B.
Considerthefollowing
procedure:
quad(A,B,C
,sign)
{disc=B
*B-4*A*C;
if(disc=
-
Exercise:Drawthecallstack
foreachof
thefivepointsof
execution.Assumequadisthe
mainfunctionintheprogram.
CSIS, BITS, Pilani3
return
(-B+sign
*sqrt(disc))/(2*A);
}
Callsequence:
1.
quad
2.
quad
-->printError
3.
sqrt
5.
next);
len(ls){
len_
tl(ls,0);
} len_
tl(ls,acc){
CSIS, BITS, Pilani5
}
if(ls==null)returnacc;
elsereturn
len_
tl(ls
->next,acc+1)
Exercise:
Drawthes
tackforlen(ls)
wherelshas4elements
Exercise:
Drawthe
stackfor
len_
tl(ls)
wherelshas4
elements
7/30/2019 Lec7(Quick Sort)
6/12
FUNCTION
CALLOVERHEADANDRECURSION
Observationsfromtheexample:
Doyou
needthecallfram
esonstackforlen_
tl?
Foratail
call,
thereisno
continuation
i.e.
no
computationtobedone(withinthe
callingfunction)
afterthereturn
8/22/2009 Sundar B.
i.e.
no
contextinformationisneeded
i.e.
no
stackframeneede
d
Foratail
recursivefunction/procedure,
Onlyonecallframeisne
eded
Argu
ments(values)can
beusedtoupdate
parameters
(variables)onthesame
frameforeveryca
ll.
i.e.
Costofatailrecursivefunction/proced
ureissameasan
iterativ
eprocedure.
6CSIS, BITS, Pilani
7/30/2019 Lec7(Quick Sort)
7/12
TAILRECURSIONELIMINATION-EXAMPL
E
len_
tl(ls,acc){
if(ls==null)returnacc;
elsereturn
len_
tl(ls
->next,acc+1)
len_
tl(ls,
acc){
B:if(ls==null)returnacc;
else{//ls!=NULL
ls=ls->nextacc=acc+1
7
goto
B;
}}
len_
tl(ls,a
cc){
while(ls!=null){
ls=
ls->next;
acc=acc+1;
} returnacc;
}
7/30/2019 Lec7(Quick Sort)
8/12
QUICKSOR
T-CALLSTACK
OVERHEAD
Consider
thefollowingim
plementationo
fQuickSort
voidquic
kSort(Elementls[],
intstart,
intend)
{
if(start
Top Related