Algorithm Lecture5 Sorting 2
Algorithm Lecture5 Sorting 2
Algorithms
Lecture 5
Sorting–2
Sorting
Algorithm - 2
Divide and Conquer
paradigm
original problem
In most algorithms, either the divide or the combine
step is trivial
An Example: Merge Sort
into non-
Merge Sort – Example
Original Sequence Sorted Sequence
18 26 32 6 43 15 9 1 1 6 9 15 18 26 32 43
18 26 32 6 43 15 9 1 6 18 26 32 1 9 15 43
43
18 26 32
18 2626 32 6 43 15 9 1 26
18 26 6 32 15 43 1 9
15
18 26 32 6 43 15 99 11 18 26 32 6 43 15 9 1
26 32 15 18 26
43
32
18 26 32 6 43 15 99 1
Merging Two sorted Arrays
Merge Sort
Least number of comparisons occur if each entry in the left
subarray is less than all the entries in the right subarray
T(n) = O(n lg n)
p: Pivot (start element)
q: last element
x:Pivot value
i: Boundary between
the elements less than
pivot and greater
than pivot
j : Boundary between
the partitioned and
unpartitioned part
From p+1
till q
Swap if A(j) less than
pivot
Running time analysis
Worst-Case
(Data is sorted already)
„When the pivot is the smallest (or largest) element at
partitioning on a block of size n, the result yields one empty
sub-block, one element (pivot) in the “correct” place, and one
sub-block of size (n-1)
„Recurrence Equation:
Solution: O(n2)
O(n logn)
Quick Sort vs Merge Sort
For simplicity, consider the data in the range
•0 to .9
•Input data: 2 ,5 ,7 ,2 ,1 ,4 ,1
Take a count array to store the count of each unique
•object .
•Index: 0 1 2 3 4 5 6 7 8 9
• Count: 0 2 2 0 1 1 0 1 0 0
Loop 1
Loop 2: A C
Loop 3: Accumulate C
Loop 4: A C B
J=4 C((A(4))=C(4)=5
A(4)=4
B(5)=4
Analysis
Name Best Average Wo rst
Quicksort
Merge sort
Heapsort
Inserti on sort
Introsort
Selec ti o n sort
Timsort
B u bb l e sort
Sm o o ths o rt
Strand sort
Cocktail sort
C o m b sort