In: Computer Science
Following is the algorithm of Quicksort for sorting an array of integers in ascending order.
Partition(numbers, lowIndex, highIndex) {
midpoint = lowIndex + (highIndex - lowIndex) / 2
pivot = numbers[midpoint]
done = false
while (!done) {
while (numbers[lowIndex] < pivot)
lowIndex++
while (pivot < numbers[highIndex])
highIndex--
if (lowIndex >= highIndex) {
done = true
}
else {
temp = numbers[lowIndex]
numbers[lowIndex] = numbers[highIndex]
numbers[highIndex] = temp
lowIndex++
highIndex--
}
}
return highIndex
}
Quicksort(numbers, lowIndex, highIndex) {
if (lowIndex >= highIndex)
return
lowEndIndex = Partition(numbers, lowIndex, highIndex)
Quicksort(numbers, lowIndex, lowEndIndex)
Quicksort(numbers, lowEndIndex + 1, highIndex)
}
(i) Re-write the code of Quicksort so that it sorts the array of integers in descending order. Writing the specific lines of code which should be changed is sufficient.
(ii) What is the worst-case runtime of this Quicksort algorithm?
i)
Code of Quicksort that sorts the array of integers in descending order is as follows:
Partition(numbers, lowIndex, highIndex) {
midpoint = lowIndex + (highIndex - lowIndex) / 2
pivot = numbers[midpoint]
done = false
while (!done) {
while (numbers[lowIndex] > pivot)
lowIndex++
while (pivot > numbers[highIndex])
highIndex--
if (lowIndex >= highIndex) {
done = true
}
else {
temp = numbers[lowIndex]
numbers[lowIndex] = numbers[highIndex]
numbers[highIndex] = temp
lowIndex++
highIndex--
}
}
return highIndex
}
Quicksort(numbers, lowIndex, highIndex) {
if (lowIndex >= highIndex)
return
lowEndIndex = Partition(numbers, lowIndex, highIndex)
Quicksort(numbers, lowIndex, lowEndIndex)
Quicksort(numbers, lowEndIndex + 1, highIndex)
}
ii)
In the worst case the list will be traversed completely and the comparisons will be done throughout leading to n2 time for n elements.
Therefore, the worst-case time complexity of quicksort algorithm is O(n2).