Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

#PROOF OF AVG.

TIME COMPLEXITY OF QUICK SORT


In , we first take the pivot (the first element of the array) and
compares the other elements of the array with the pivot and
redefined their position in array such that elements which is
lesser than pivot is placed in one side and other are placed in
other side of the pivot

i n-i-1

First pointer
second pointer

My first pointer goes from a[1] to a[i] and compares the each
element with a[0]
Time for comparing all elements in a[1] to a[i] : i
Similarly,
My second pointer goes from a[n] to a[n-i-1] and compares
the each element with a[0]
Time for comparing all elements in a[1] to a[i] : n-i-1

Adding these complexity : i + n-1-i = n-1 ˜̴ n


Considering time complexity of comparing and swapping
Adding time of swapping has no change in order
Let swapping is done in k*n where 0<K<1
Adding n+kn = cn where c = k+1
Total time : cn

Now we break this array in subarray


One Subarray consists of elements a[0] to a[i]
Time for doing previous checkup : T(i)
Similarly ,
For other second subarray
Time for doing previous checkup : T(n-1-i)

Recursive function for time


T(n) = Ʃ T(i) + T(n-i-1) + cn from i=0 to i=n

In AVG. CASE
We take all possibilities
After ith iteration ,we assume that ith subarray is sorted
and rest of the subarrays and previous arrays are not sorted

Probability of having ith sorted array and rest previous and


further not sorted : 1/n

*Avg. time compexity*


T(n)=1/n(∑(T(i) +T(n−1−i) +cn)) from i to n-1

= 2/n(T(0) +T(1) +. . .+T(n−2) +T(n−1)) +cn,

nT(n)= 2 (T(0) +T(1) +. . .+T(n−2) +T(n−1)) +c(n)^2 eq.(1)

the above expression holds for n-1 also


(n−1)T(n−1)= 2 (T(0) +T(1) +. . .+T(n−2)) +c(n−1) ^2 eq.(2)

Subtracting 1st and 2nd ,

nT(n)−(n−1)T(n−1) = 2T(n−1) + 2cn−c ≈ 2T(n−1) + 2cn

Thus,nT(n)≈(n+ 1)T(n−1) + 2cn


Or T(n)/n+1=T(n−1)/n+2c/n+1

T(n)/(n+1)−T(n−1)/(n)=2c/(n+1)
Expanding both of equation

T(n)/(n+1)+T(n−1)/(n)+T(n−2)/(n−1)+. . .+T(2)/(3)+T(1)/(2)

− T(n−1)/(n) − T(n−2)/(n−1) −. . .− T(2)/3 − T(1)/2 − T(0)/1


= 2c/(n+1)+2c/(n)+. . .+2c/(3)+2c/(2),

T(n)/(n+1) = T(0)/(1) + 2c/(1/2+1/3+. . .+1/(n)+1/(n+1))

[ using Taylor series of log(n) : 1 +1/(2)+1/(3)+. . .+1/(n) ]

≈ 2c(log(n)) ≈ c′(log(n))

T(n) ≈ c′(n+ 1) (log(n))

Avg. time complexity of quick sort is O(nlogn).

You might also like