CSCE 210 Dr. Amr Goneid Exercises (7) Sorting Algorithms
CSCE 210 Dr. Amr Goneid Exercises (7) Sorting Algorithms
Amr Goneid
Exercises (7) Sorting Algorithms
________________________________________________________________________
1. Consider the algorithm for the sorting problem that sorts an array by counting, for
each of its elements, the number of smaller elements and then uses this information
to put the element in its appropriate position in the sorted array:
Answer:
A tracing of the algorithm will produce:
0 1 2 3
A 4 3 8 5
Count 1 0 3 2
S 3 4 5 8
The array element comparisons will be inside the nested (i) (j) loops. The number of
such comparisons will always be (n-1) + (n-2) +......+1 = n(n-1)/2 so that the
complexity is O(n2)
________________________________________________________________________
2. Sort the list E, X, A, M, P, L, E in alphabetical order by selection sort and by Bubble
sort.
Solution:
Sorting by Selection Sort will proceed as follows:
E X A M P L E
A X E M P L E
A E X M P L E
A E E M P L X
A E E L P M X
A E E L M P X
A E E L M P X
• Find the exact number of array element comparisons done by this algorithm in the
best case and in the worst case.
• Find the exact number of array element moves done by this algorithm in the best
case and in the worst case.
• What is the complexity (Big-O) of the algorithm?
n
{A useful summation: ∑
i =1
i = n(n+1)/2 }
Solution:
The analysis of Insert Sort is given in details in the slides of Part 8a
________________________________________________________________________
4. The array of integers: (4 , 4 , 8 , 5 , 3 , 6 , 1) is input to the Mergesort algorithm.
• Trace the algorithm to sort the array.
• What is the complexity of the algorithm when sorting an array of N equal
elements?
• Is the algorithm stable?
Solution:
• The array sorting will proceed as follows:
4 4 8 5 3 6 1
4 4 8 5 3 6 1
4 4 8 5 3 6 1
4 4 8 5 3 6 1
4 4 5 8 3 6 1
4 4 5 8 1 3 6
1 3 4 4 5 6 8
Answer:
For random input, Insertion sort costs O(n2) and Quicksort costs O(n log n).
Hence, Quicksort is faster by a factor of n/ log n = 50,000
________________________________________________________________________
7. For quicksort with the median-of-three pivot selection, are strictly increasing arrays
the worst-case input, the best-case input, or neither?
Answer the same question for strictly decreasing arrays.
________________________________________________________________________
8. The array of integers: (4 , 4 , 8 , 5 , 3 , 6 , 1) is input to the Quicksort algorithm that
uses the Median-of-Three as pivot.
• Display the array step by step as it is sorted by the algorithm.
• What is the complexity of Quicksort when sorting an array of N equal elements?
________________________________________________________________________