0% found this document useful (0 votes)
12 views19 pages

Quick Sorting

Uploaded by

2k23.cs2310702
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views19 pages

Quick Sorting

Uploaded by

2k23.cs2310702
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

QUICK SORT

have an average rUn time af


develo ped by c.A.R Hoare in 1962, Sosfingmetod.
Beter
and treated as a
o( mlag")
we can d r a a
Yom the previous soting method stuied so ar, one
one o) these
list with any
Conclusen tht soin a smalles ( for ex, i te
Jarger list
Jaster than a isdoubfed, sotRng tmea
Mumbey elements in the ist
fmercose quad vobicaly
Hence be divdig
mumber af smaller lits,
aJarge Aist into a combine the
amd then
Sot then seorae St soted.
Hes ultsS to

This
DIVIDE-AND- CoNAUER Approach
c.4.R Hoare adopid
DIVIDE AND CON GVER APPRDAH.

ple of divde - and- conqucy shateg s to 30red


he privci he poteg.
the swmaluey inslences
pblen by
mumbey of 6maler sub prnblem.
14) Divide :- divide lorge problemiito a
is not smal then decomboie
1f the gub-þoblem decompositioy umtl all sub-pneiem
Fhang ond tontinue the

so that each subpnblem


techntque
(o) Conquri- fnd a putae be solved
(1, 2,5,.. . ., n can
f
yeluions ts au salo-prnalema to
yyt
the yeut
Combie the a
(9 Combine i- Combire
the fiad Golukioy.
e
Pooblem

Divide

conquer

combine

SoluHon

ivide and Conquk Shaksay


prpcedure fs 4olowed do acheie tthese tasks.
In
gnad, a Hecursive
Yame wots divide- and- Conque approach Can b8
Ihe ecurS0VE
stated as belowi’
solred.
to be
DvPde -and- Conquer CP) I| P isaproblern
n denotes the sice o7he poolerg
1. n= Size(P) u minimun size e a sub
the desira ble dition.
I| MIN denotes the termimaHon con
a. 1f (ns MIN) problem and also
smallest mit using a simple metbod
the
S= Conquer( P) u Solve imto 1sub-probtems
do bvide P
5. Else ,2, P3,..,P?
4. For each Pi e fP, fe,.., Pn t do I1.Cal|
S;= Divide -and- lonquer (Pi)
Sn) | Cormbne al solutions.
5. S= Combine (Si, 32
6. getwTn (5)
DiVIDE -AND-CON QUER ApPROAH IN QuCK SORT

Quich Sert (A, frst, lost)


I| TerminaHon condition.
1. I[ (fst< lest) then
tHon list atP
p laition (A, fixt, last) I Pavti
8. Gicksort (A, fiast, p-) hRecuasive call os delt sut
4. Qucksert (A, p+4,last) Recursive call tor rigtt Sobtree.
5. Retum

too sublists A[1,-- p-1]


FarHtoy the líst ALL4-- n] înto
that
Lp+1,-.., n1 (rigtt siktist) sich
Cgt suotree) and A »p-]is less thay
elemetts n the subr list. AL,--
cah Alpt!,-n
each elemerst n the sutlist,
equal to
ALPI and
than ALp.

Conquer i’ Ar1,-- P-] nd ALptt,J


’Sot the too sublfst sublist is'a itst to beoted
1f each staegt
the Aame divi de-and- Conquer
amd yolloiuíng ei ther zro.ox one elemen
zub-lists contaiy
Unti
no wot is
Meeded
are sorkd in placey
’ 5ince the sublists task Combine in the vick sort
is, the
to Combne them. hat
is Implidt.
Partition Method in Quick Sovt

Sieps
1. Joc = let
2. while ((test(nig)) do
3.
while (Aloc] s Avigti) and (loc (right) do
4.

5.
End While
6.
14 (AEtoc]> ATvigt]) then
4. Smp (A[locJ, A[rightJ)
8.
Joc Tight
9. legt Jet+1
lo. End |f
While (ATloc]ATlejtJ) and (lacotept)do
l2.
legt= Jet t1
13. Endwhile
14.
1f-(ALiocJ<ACleftJ) then
15. Swap (A[locJ,lefti)
16. Joc Jeft
1+.

12. Endlf
19. Endhile
20. Peurnlec)
lLLUSTRATION Of THE PARTITION METHOD
scan tom right to Je7t
loc
8822

legt

4) At the boginimy te porhtion loc

22| 4444 6644


33

1
legt
talet tohile the pivot ik
Scamnimg tom rigut
a he
loc

22 44 44c
66 8 8
33 55
ght
Qhle
rg
OAter the scamning trom Jet to
scattinggrmvtntto let
at Tg.Teoty begins he loc

33||| 2244 44

.
loc

35112255 44 44 66 77 28

let rigut

te piodt u at ngut Next,it bejina

nloc

33 11 22 44 9966

onde tu
Condihey violales.

ALORITHM &VICK SORT


Skps:
7 leyt and rigit ae teoo pointers to
a. 1(Jet <rigtt) then loeate panitioms at Aet qnd
B. Joc Poritien (A, Aeyt, right) igud rupehvely
SORT (A, Ae4t ,Joe-1) I/ Perfom auickSot over let subhe.
GvIK rigt subhe,
Joc+1,riat) / Peom uickSeot over
5. 6vursoRT (A,
6. Endit
4.
IME ComPLEKITY OF Quck SoR.
from 4he Qulch Sort ’ Time Comþlexity Guick Sot
depende ARTITIONN and CALs of two Auic7Sot on too
lisfs amaller sizes.
.total timeto sot nelements.
P(h)>
then we wite,

|Tu)=PCw) + T(ni) +T(W2)|

’ Noke that basie optration iy he Quich Sot echniqve is comparnsem


amd

Guidk Sot -’ basealy a Mepetition o pasitian methads.


Let Ccn) and Men) denoles the numbe ot Corn panfsoys ayd moremens.

Ten)= (n) + MCM)


Theye ae thee cOtes the knpat rgement
or which we caleulate the time cormpexities3

Case4: Elenmonks in Hhekt are sved un stconding.Qder No- Comrsons.


Im this case, the pasiioy meyrd Hequires only ohe scan trom
Tght to lgt with n Comparisons. mthis cat pashhan Sublst
element
oith 4
degt yemam empty omd ight Bubtree
KEcyRRENCE KEUAIo
t((n-)wihec) and clo)=o
CCn) = n-
get
Expandig itn RecueneRelatiem , we
tt2t1
Ccn) (n-1) +(4-2) +(n-)
Numbey s Movement
case.
No
erChomge opevahion ie imvolved m dhà
Hyce the mumbuy o movement M() givby
MIM)=D

CasE2: Element in the list or ih Descendiglde.


O No compantson
IM this case , thepontition methed requi res m4
Combaicos.
8ublists are
Unlike Hhe case 1, in this case the non empty
C*Tnaivey det subigt and righnt sub-ist.
Reursire cal
Can beeveDfed for eveny odd numbered evenmmbered
Bub list i's empty wohe aa tor exct
ieusive cal the de Sublit mCmgy
C(n) dencles he nof omþaDsoms mthio case, ue hare
NOW IH
CCn) =n- +cCn), with C=(co) =o
Relaio
* ErpadingReurene
Ccn)> n)+(n-) +(u-3)t- +2+|
n(n-1)
(9) Numbey Moremerk

orchanged opofon i each odd numbered BeuSiNe Call.


ig
Singie
’ No trvolred during engeven yumbered Becursire Cal.
We have he
reusions,

M(n) = nis odd

2, &even

the Bame côn bereþresented

CASE3: Elements m the iat are stored in Bandom Oder

ti-y (n-i)

To ind the nal


nal beth the prvot element, we meed (n-) comparsons
n ihe pauio mthod on a Jist oth nelement.
Now assume that the patition meyod yinds ne poghton
yor dhe pivot lemest tn t Teststuo subiia:
subtree = 4- elements,
LEPr Gug-usT witn (i-1) elemets and
lemento mthere too Autats are
Now, all perm ülalioys demiats
We asune that each possi He position -for the pivot element is equag

That is value oi hos any value


Yalue q w 1 ad n wih a

n hu Case as
he ve uee equatom tor the mo com parison3

C)= (n-)ci-) *(tm-t)] with c)=ctoj-0

Ahove eguaten con be Atmplified as btaed belei


The tum Ci-) varies uom C(o) to (((-)
whaeas C(n-i) vares tnom C(n-1) to (to)
over tne itlihe, hange t summaion senita,
that is, (=1 to n-.

same seis.
l otherwords , two terms conhibwe the
Bo me con Aimpiy the Reuyrrene KRelaton

CCn) = (n-i) +2 (ci). jor m1


j=)
Replacíng n by md , we have
n2
c(n-) = (n-2) + 2

-2

Now M-cln)- (n-). c(n-) e n(n-) +2S ci)-(n-) (n-2) -2s cci)

n-2
=(n-1)-(w-n-2) +2.

2 (n-1) + 2 C(n-1)

m.ccn) = 2(n-)+ (n+1) . c(n-)

2(n-1) +C(a-)
n(n+)

let ’
c'cn) = <(n) Then
m+)

c'cn) = c'(n-1) + 2(n-) , with c'ci)=o


m(n+)
can be
This iss the stmplijied vexs ioy t Beurence Belaton amd
sel ved fust by simgle erpmtoy.
c'cn) = 2(i-1) 2(i+1) -4 4
i(ii) ji+))

i=) i(i+1)

M
This is Haymonie Seres
whose sum. is j!
(4)(;-4)
Hence we
e'n) =2legen tos7*) -4
Bubshtuting c'en) = ((n) we gt
Ctn) =2(n*) (Jogen to-574) -4n

Assume element n the ist aranged nsuch aoay


that evot intane paition method exact
pantrtions the itrino 2 dats qualaice.
The Becurrence Belation
Cen)= (n-)+2((/2)
Expamd the, heurence Aelatiow
ccn)= (n-)+ 2c(n/)
=

(n)+2||-)+<()]
For sthe salke a simphuy let m=2 tor some Ko
Auo vsing CCo) =0, wego

((n) =(n-j ++(n-2) +(n-2)+ -- -+ (n-2k")

2-1

M+1 M=2

6 Nunmbey Moxemta
Let the docalon pivót be i , ohee lsisn.
Then ottr the þanhion ,the pivot element its guaroteed fobe
plaed in locaioni wth 1... (i-)) elements in the det
Bub hree nd (i+)., n elemens
should
The umber o exhonges that is meceemy to do tha
Mot vceed (i-1) or each G} ()elemests less tho the prvot
elements
opefoHons
-et us denote Mcn),the averae nunber oym.echonge
hen we have
dist stze
dome by he avf oSort om the

Mcn)+i-)+mi)+Mo)]
j=l
Soted
rdus.
Remask
hton
fo
blus
locaPoy solve
wene
movements u) do Memory
Sn)=4
any
toca s()=).
joltoucd
thehe sn=
ny
of in es (logentoY
mo. (Similx
placed M(i). Morement Men)=
2(M+).
all
n
Gorne8 4n
Belaton
Reuene
the 0s MCn)
t be is
average loa obBaiyed ALe.
may bability s,barison
M(n)
=+ n(n-1)
CCn)= C(n)=
m(n-) (logen
to-S7)
the pivot pro (n+4) SoRr Com
parison CCA)=
2(n+1).
Hecumenre
dhs
PMCe be AuLCK 2 2!
taken
the a
2. eom can
-4n
2
soith = DE
that whfh M(M) ANALYSLS
have
n
o.
he Caes
we uning
tmd M(n), Cose 1ase Case
e
4and
Here Oss
°
o(nlg)
Sot
Cose
Worst
Averoge are complentyhedivide Quick o(nlog),
Rermaak
Case
Worst
Bet] ease the
Pst
the case
ott
= the
aeroe
aluoa y t+o6)-&en is
n case
lemens
Sort wot. behavfour hat
Quick TU).o(nlga
) Sort. methd the
o(n)
T(h) o(n)
TUn)= Order.he
Comlexty bubble that estcose
tht
dhe 4he paktion caseayn
qComploity ohen or case averoge at
Bevese Aeleion 4ctn) g
) to-544)2<[nlgn-n+4] ocu°t the that
the
emethat
ene
chen
fn to
=
ase in mserion. ad malgsed
thst
that
Time
(n-1)
Tn)c
<(ntn).
T (logen posdibe tomplrity
malysed
cose
concude
Ruilime,
T() Worst halt.
haty very
2 (n+1)
-T(n)
TUn)=4c as ts kcely also
seensosed
areody istomplerity
Bad case Thestore
oy have
have with
time
s Best ints
A JSst We
We lWe
-
Memory Requivement Quich Sort

What ever it pndues or poceduwe , it as aluays mecessorg


to maintam a stack -why a atatk s oquired?
An aysww. to this qocahon ’ is that , a gtah a
-’ to store all sutb lists (yothing but the too borndarg
Indexes the dit) wtch à yd to be puecessed.
stacs is pushed witt two bo undary fnd exes of th
Inikelly, he
Aist md st eun¡n starts with the eall to thi Jit.
imput
pushed
pahtHon , at podues tuo subliuks ,wtrch are
snto the stack.
hen Pops a dist, eall qutch sot n the dt popped pushes
too lits n pavtioy ,and so on. These sleps are repeated
umu stack is emp
no ob
I+ (s evident that the size o the btack, depends upon the
Sub sutt nto wtieh a ist may be pitimed touaTas e
Compielar the potg
and tuo puhu arzioy,thereby
tNo ever cal make one poP
Ds the
m otho, words, sie ot the Back hould be as davge
No. Keurive Cals fovolred.
howthe uts
No- Reuneive Casl , housever depends upon
Portiioned dusiny Reurs'oy.
Can be tha least yumben of
onalgsed that Becursive cals
Occuos ohen each Heursioy spits at
ual halwes.
no Jo (neaty
m Such acse maximum size o the stack wowld be
` the gumbez elements
in he

eth sokd in
Dn the othelhond i t tbe inpt it o
On
4sCENDING or DESceNDINE ovder then the yumber
be exacty n. on thi case, theye wil be
cay wiu be

at most one eny W the stack. hiss because ONE SUe-LiSTS


,
Oiu alays be emot , and ftTt pushes the non empty aubHI|letsthete
tis contiyues
Ohfch popped in che' nest Beursioy ayd Bubsts.
Sngte element nthe mon-enptg
constder'ngorst Case Aibiaion, the Atovge spae
So with melements u
eguenent sty to dort atst

occurs ohen list pavitioned into


Maxi mum No.e Beursion
MAXIMUM ANO MINIMUM NUM BGR OF BecuRSIve CALLS
To SoRT A usT OF N ELEMENTS USING QVICK SoRTL
Is 2N-1. AND N, ReSPeCTIVELY

PROof:
MaN) mum Mo. o} Reeursion occuns when each recurcive cal
pntibon the list ito equal ot two sub-lists.
equal To
o4 neas equal
For Simplicity in the pre, (et us Qusume that N 2
Iheye K>o a a tonsBant.

FigsT RecuRSION BeNS With the list o4 size N.


IH paoti Hoys tthe list into twosublists each ot
Thu wil be followed by the calls 'af two Becu rslons eath
n he the tioo sublists, ohfch twy Create into Tow
Bublists
each sire 4 - ,
each he
Net, theye oill be Hout Becursire Calls onm
fouy lisls. This wiu Continue tis a sublist tontains
N/2K.
Singe elemuts, that is sire o the st. beomes
Ihus Maimum Muber of Gecursive Cals mOrder to
Sing auicu SogT. is
Kmax 1+2+ 4 +.-.. +2
= -1 (solve uslng g
2N-1.
ea
plo
.i n t
lerel No. of recu
I20
Reursion
this
at 2 =2
thedist
the
For 4=22
6n -2.
8 -23

These st ore tobe


Stored in the slack
Reunim calls and requiremeát aSiacksize
Maximun umbty af

Minimum No- o Recursion cals equirement tslack sie.


ON The othey hand , minimum munbe ot; Rersive Calls occur
Sosfed in AscENDING
whey au elemests fh the fopit Ifst is alveady
or DesceNDINGT ORDER
AsceDING DRPeR.
Le us asume that the list Bosted n
each Recusclve cal portions the lfsts so that the e
tM thu COse,
demet
S0bee ist is empty and Riat Bubistt contams one
the it tothe call o the KeursioM.
less thay the size þrior
Tsee with maximun
Buch a Reursin Tree is a skewed
Thus No'Recursive call giren bt
Bmax =.
poim Level
reutsioniatatthis
c a lonthe 1
forthe
1

2
this it sto 1

1
At this þoiyt the list contains
shgle elemeut henco
o remslon

You might also like