Вы находитесь на странице: 1из 9

Quick Sort Algorithm

Quick Sort Algorithm

To sort an array S
1. If the number of elements in S is 0 or 1,
then return.
2. Pick any element V in S. This is calle !i"ot.
#. Partition S$%V& 'the remaining elements in
S( into t)o is*oint grou!s+

S
1
, %- S . %V& / - 0, V&,
S
2
, %- S . %V& / - 1, V&
2. 3eturn %4uickSort'S
1
( follo)e by "
follo)e by 4uickSort'S
2
( &
Quick Sort Algorithm
Quick Sort Algorithm
QuickSort'A, left, right( {
if (right 1 left( then {
!i"ot , Partition'A, left, right(5
QuickSort'A, left, !i"ot$1(5
QuickSort'A, !i"ot61, right(5
&
&
Quick Sort Partitioning
Quick Sort Partitioning
Picking the Pivot:
A , 7, 1, 2, 8, 9, #, :, 2, ;, 0

Pick three elements ranomly an


the meian of these three numbers
is the !i"ot.
Partition Algorithm
Partition Algorithm
Partition(a[ ], left, right ) {
int i, j;
int Pivot = (left+right) / 2;
Swa(![Pivot], ![right]);
i = left; j = right " #;
Pivot = right;
while ( i $ j ) {
while( a[ i ] $= a[Pivot]) i++;
while( a[ j ] %= a[Pivot]) j" ";
if ( i $ j ) S&!P(a[i], a[ j ]);
'
Swa(![ i ], ![Pivot])
ret(rn i
'
Analysis of Quick Sort
Analysis of Quick Sort

)or anal*+i+ a++(,e a ran-o, ivot (no


,e-ian"of"three artitioning) an- no
c(to. for +,all /le+0
1(2) = 1(#) = #
1(n) = 3(nning ti,e of two rec(r+ive call+
+ linear ti,e +ent in artition +
con+tant ti,e er ivot +election0
1(n) = 1(i) + 1(n 4 i 4 #) + cn
&here i = 5S
#
5 i+ the n(,6er of ele,ent+
in S
#
<orst$=ase Analysis of Quick
<orst$=ase Analysis of Quick
Sort
Sort

1he ivot i+ the +,alle+t ele,ent


all the ti,e0
12 #2 :9 99 12
12 #2 :9 99
#2 :9 99
:9 99
99
<orst$=ase Analysis of Quick
<orst$=ase Analysis of Quick
Sort
Sort

1he ivot i+ the +,alle+t ele,ent all


the ti,e0 1hen
i = 2 an- if we ignore 1(2) = #, which
i+ in+igni/cant, the rec(rrence i+
1(n) = 1(n 4 #) + cn, n % #
&e tele+coe thi+ e7(ation th(+
1(n 4 #) = 1(n 4 2) + c(n 4 #)
1(n 4 2) = 1(n 4 8) + c(n 4 2)
99
1(2) = 1(#) + c(2)
!--ing ( all the+e e7(ation+ *iel-+

=
= + =
n
i
n O i c T n T
2
2
) ( ) 1 ( ) (
>est$=ase Analysis of Quick
>est$=ase Analysis of Quick
Sort
Sort

:n the 6e+t ca+e, the ivot i+ in the


,i--le0
12 #2 78 :9 99 107 12
78 99 107 12 #2 12
#2 99 107 12
>est$=ase Analysis of Quick
>est$=ase Analysis of Quick
Sort
Sort

:n the 6e+t ca+e, the ivot i+ in the ,i--le0

1o +i,lif* ,ath, we a++(,e that


1wo +(6/le+ are each e;actl* half the +i<e of the
original, altho(gh thi+ give+
Slight overe+ti,ate, 6(t thi+ i+ acceta6le
6eca(+e we are onl* intere+te- in a =ih">h
an+wer0

1(n) = 21(n/2) + cn0

1he +a,e rec(rrance *iel-+ 6* ?erge Sort


therefore

1(n) = cnlgn + n = >(nlg n)

Вам также может понравиться