Professional Documents
Culture Documents
Online Class 10-Quicksort
Online Class 10-Quicksort
Array locations in
blue have been pivots
in previous recursive
calls, and so the
values in these
locations will not be
examined or moved
again:
Here is how the entire quicksort algorithm
unfolds.
Array locations in blue have been pivots
in previous recursive calls, and so the
values in these locations will not be
examined or moved again:
How many operations to do
partitioning?
n times
Theta(n) is the time taken to do
partitioning
How much times does quicksort take?
Depends on whether the partitioning is
balanced or not .
If balanced … as good as merge sort
If not balanced …as bad as insertion sort
All stages have balanced partitions
On each level of the tree order(n)
computations are involved ,and there are
lg n levels for the tree
Best Case
By equally balancing the two sides of the
partition at every level of the recursion,
we get an asymptotically fast algorithm
Worst-case partitioning
n-1 elements and one with zero elements
(???)
Let us assume that this unbalanced
partitioning arises in each recursive call.
For the partition with 0 elements
………….
Since the recursive call on an array of
size 0 just returns,
T(0) =Theta(1)
The recurrence for the running time is… time to partition
+time to sort left part+ time to sort right part
Worst case partitioning tree
Thus, if the partitioning is maximally
unbalanced at every recursive level of the
algorithm, the running time is Theta (n^2) .
Therefore the worst-case running time of
quicksort is no better than that of
insertion sort.
Moreover, the running time Theta (n^2) .
occurs when the input array is already
completely sorted
—a common situation
but …..in which insertion sort runs in
Theta(n)time.
When does worst case appear?
Worst case …
Already sorted
Reverse sorted
Recollect that …..
For insertion sort ,sorted elements is the
best case ,but not here
Average case
The average-case running time of
quicksort is much closer to the best case
than to the worst case, as the analyses
will show.
Average case
The key to understanding why is to
understand how the balance of the
partitioning is reflected in the recurrence
that describes the running time.
An average case 1:9 split
Example
1 2 3 4 5 6 7 8 10 9
How many levels ?
log n to the base 10/9
Which is order (lg n)
Average Case—alternating between
good and bad divisions
Randomised quick sort
Randomisation is good for algorithms
which have good average case time and
bad worst cases
We don’t know the pivots ..
And each time the algorithm runs, the T(n)
changes
Randomised case
It is the case when we choose any random
element as the pivot element
Average case ( randomised)
We get an average case where we..
average sequences of random numbers
For the same sequence if we calculate the
time taken for all days for a period and
then take the average time …
This is what is meant by the average case
…or… the split toggles between a good
and bad splits