Tutorial 8 - Comp352 WINTER 2018
Tutorial 8 - Comp352 WINTER 2018
WINTER 2018
OUTLINE
o Quick Review comparison-based Sorting
o Merge Sort
o Quick Sort
o Stability
o Linear-Time Sorting
o Bucket-Sort
o Radix-Sort
o Problem Solving
MERGE SORT
Idea: Mergesort is a divide and conquer algorithm. The fundamental operations in
this algorithm are dividing the array into two sub-lists with equal length and merging
these two sorted lists.
Reference: https://www.geeksforgeeks.org/merge-sort/
QUICK SORT
Idea: Quick sort is also a divide-and-conquer algorithm. Similarly, the algorithm spilt
the input array into two sub arrays in each recursive call and conquer the two sub
arrays with the same method.
Example:
For simplicity, consider the key in the range 0 to 9.
Input data: (1, 𝑣1 ), (4, 𝑣2 ), (1, 𝑣3 ), (2, 𝑣4), (7, 𝑣5 ),
(5, 𝑣6 ), (2, 𝑣7 )
RADIX-SORT
We want to sort entries with keys that are pairs (k, l), where k and l are integers in
the range [0, N−1], for some integer N ≥ 2. In a context such as this, it is natural to
define an ordering on these keys using the lexicographical (dictionary) convention,
where (𝒌𝟏 , 𝒍𝟏 )<(𝒌𝟐 , 𝒍𝟐 ) if 𝒌𝟏 < 𝒌𝟐 or if 𝒌𝟏 = 𝒌𝟐 and 𝒍𝟏 < 𝒍𝟐 .
PROBLEM SOLVING 1
Given an array A[1…n] with each element in range [1, k] . There is an element that
appears at least n/2 times in this array. Please find out this number.
For example:
A[1..n] = {1,2,3,2,2,2,5,2,4}
Output:
2
PROBLEM SOLVING 2
Given an array A[], write a function that segregates even and odd numbers. The
functions should put all even numbers first, and then odd numbers.
Example:
Input = {12, 34, 45, 9, 8, 90, 3}
Output = {12, 34, 8, 90, 45, 9, 3}