Professional Documents
Culture Documents
CSN-212: Design and Analysis of Algorithms Tutorial 3 (Sorting Techniques)
CSN-212: Design and Analysis of Algorithms Tutorial 3 (Sorting Techniques)
SOLUTION
Q1:
Suppose an array has four times occurrences of “0”, five times of “1”, and three times of “2” in any
order. The array needs to be sorted using swap operations (note: the elements that are swapped
should be adjacent).
(a) What is the minimum number of swaps needed to sort such an array in the worst case?
(b) Give an ordering of elements in the above array so that the minimum number of swaps needed to
sort the array is maximum.
Ans:
Since swaps are needed to be of adjacent elements only, the algorithm is actually Bubble sort.
In bubble sort, all smaller elements to right of an element are required to be swapped. So, if have
ordering
[2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0], then we need total 47 swaps, and this will be the worst case.
----------------------------------------------------------------------------------------------------------------------------- ---------
Q2.
If we use, straight two-way merge sort algorithm to sort the following elements in ascending order:
21,48,16,9,10,5,41,31,13,18
then after second pass of the algorithm, what would be the order of elements?
ans:
Q3.
Using heap sort, how many number of elements that can be sorted in Θ(log n) time ?
Ans:
Q4.
Suppose you have ‘n’ lists, each having ‘m’ integers sorted in ascending order. How much time (in
terms of O()) would be needed for merging these lists into a single sorted list?
ans:
Q5.
Ans:
1st pass:38,53,13,12,26,93
2nd pass:38,13,12,26,53,93
3rd pass:13,12,26,38,53,93
4th pass:12,13,26,38,53,93
5th pass:12,13,26,38,53,93
Q6.
Suppose M,N,O,P,Q are sorted sequences having lengths 20, 24, 30, 35, 50 respectively. They are to
be merged into a single sequence by merging together two sequences at a time. What is the number
of comparisons that will be needed in the worst case by the optimal algorithm for doing this?
Ans:
Q7.
Let P be quicksort program to sort numbers in ascending order using the first element as the pivot.
Let t1 and t2 be the number of comparisons made by P for the inputs [1 2 3 4 5] and [4 1 5 3 2].
respectively. Which one of the following holds true: t1 < t2 or t1 > t2 or t1 = t2 ?
Ans:
Q8.
A list of ‘n’ strings, each of length ‘n’, is sorted into lexicographic order using the merge-sort algorithm.
What is the worst case running time of this computation (in terms of O())?
Ans:
You are given the first character of each n strings. To sort it will take O(n.logn) time… in the worst
case we may have to do the above process n times so
n * O(n.logn) = O(n2logn)