Question
#2. 3-way Quicksort In class we saw that the runtime of Quicksort on a sequence of n identical items (i.e. all entries of the input
#2. 3-way Quicksort
In class we saw that the runtime of Quicksort on a sequence of n identical items (i.e. all entries of the input array being the same) is O(n2). All items will be equal to the pivot, so n-1 items will be placed to the left. Therefore, the runtime of QuickSort will be determined by the recurrence T(n) = T(n-1) + T(0) + O(n) = O(n2) To avoid this case, we are going to design a new partition algorithm that partitions the array into three parts, those that are strictly less than the pivot, equal to the pivot, and strictly greater than the pivot.
a. (6) Develop a new algorithm 3WayPartition(A, p, r) that takes as input array A and two indices p and rand returns a pair of indices (e, g). 3WayPartition should partition the array A around the pivot q = A[r] such that every element of A[p..(e-1)] is strictly smaller than q, every element of A[e..g-1] is equal to q and every element of A[g..r] is strictly greater thanq.
Hint: modify Partition(A,p,r) presented in the lecture notes and in the textbook, such that it adds the items that are greater than q from the right end of the array and all items that are equal to q to the right of all items that are smaller than q. You will need to keep additional indices that will track the locations in Awhere the next item should be written.
b. (5) Develop a new algorithm 3WayQuicksort which uses 3WayPartition to sort a sequence of n items. Again, 3WayPartition returns a pair of indices (e, g).
c. (3) What is the runtime of 3WayQuicksort on a sequence of n random items? What is the runtime of 3WayQuicksort on a sequence of n identical items? Justify your answers.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started