COMPSCI 220 – Tutorial 4 Sorting Quicksort Heapsort Quicksort Four basic steps: If n=0 or 1, return Otherwise, choose one of the items as a pivot Partition the remaining items into two disjoint subarrays by placing the items greater than the pivot to its right and all the others to its left Return the result of quicksort of the left subarray, followed by the pivot, followed by result of quicksort of the right subarray In-place, not stable 𝜃(𝑛2 ) in worst case. 𝜃(𝑛 log 𝑛) in best and average case. Quicksort Heapsort Heap is a complete binary tree Basic steps: Every parent node in a minimum heap have a node key smaller or equal to all of its child nodes. Similar condition apples to maximum heap with obvious difference. Build a heap from the unsorted input Read and output the root and delete the root node. In-place, not stable Heapsort Heap is built using bubbling up method. Root deletion using percolating down method. Add the node to the next slot available Keep swapping the new node with its parent if the heap property is not satisfied. Move the last leaf of the heap to the root Keep swapping this node with the larger (smaller) of its respective new children if the heap property is not satisfied. θ(𝑛 log 𝑛) in all cases. Quickselect Finding the kth smallest element in a given list Basic steps: Can be done faster than soring in general Very similar to quicksort Select an element in the list as the pivot and partition the list into two sublists just like quicksort Recursively search the sublist depending on k and the size of Average case 𝜃(𝑛) Question 1 (a) Perform quicksort on the following array, showing each step of working. Take the median value as the pivot, starting with 17. Question 1 Question 2 Consider a maximum heap formed by the array. (a) How would you insert the node with a value 25 in to the above heap? Question 2 Question 2 Question 2 (b) How would you delete the root from the original heap while maintaining the heap order? Question 2 Question 2 Question 3 Describe the process of heapsort, and what is the time complexity of each step. Construct heap θ(n log n) Output root and delete root θ(log n) Repeat until heap is empty n times Question 4 Find the 7th smallest element in the list 7 12 8 5 4 15 9 17 using quickselect 4 5 8 7 12 15 9 17 9 7 8 12 15 17 15 17 looking for 7th element-right list 5th element - right list
© Copyright 2026 Paperzz