Lab07 Sorting
Lab07 Sorting
Lab 7 Sorting
Learning Outcome
• Understand how Selection Sort, Heap Sort, and Bucket Sort work, and identify its time complexities.
• Understand how Quick Sort works, and identify its time complexity.
1. [30 min] The following Selection Sort algorithm is used to sort the array of 7 integers below.
Array: 38 9 38 37 155 197 65
(a) Fill up the table below based on the content at the end of each outer "for" loop iteration or i.
i maxIndex Array
6
5
4
3
2
1
(b) Implement a program with selectionSort to prove that your answer in (a) is correct.
// filename: selectionSort.cpp
1
(c) Fill up the table below and find the time complexity for Selection Sort.
2. [40 min] The following Heap Sort algorithm is used to sort the same array in Question 1.
Array: 38 9 38 37 155 197 65
(a) Fill up the table below based on the content at the end of each "for" loop iteration or i.
(b) Implement the heapSort using the following program. Verify the output.
// filename: heapSort.cpp
#include <iostream>
using namespace std;
2
if (left < arraySize && A[left] > A[j])
max = left;
else
max = j;
if (right < arraySize && A[right] > A[max])
max = right;
if (max != j) {
swap (A[j], A[max]);
heapify(A, arraySize, max);
}
}
int main () {
const int n = 7;
int A[n] = {38, 9, 38, 37, 155, 197, 65};
cout << "Input: ";
printArray (A, n);
heapSort (A, n);
cout << "After Heap sort: ";
printArray (A, n);
}
3
3. [20 min] Radix Sort is used to sort the same array in Question 1.
Array: 38 9 38 37 155 197 65
Algorithm radixSort(S, N)
Input sequence S of d-tuples such that (0, …, 0) (x1, …, xd) and
(x1, …, xd) (N - 1, …, N - 1) for each tuple (x1, …, xd) in S
Output sequence S sorted in lexicographic order
for i d downto 1
bucketSort(S, N)
(a) Fill up the table below based on the content at the end of each "for" loop iteration or i. Use N = 10.
Original array
38
9
38
37
155
197
65
4. [30 min] Perform Quick Sort on the array in Question 1. Use the first element as pivot. Assume that the
partition is stable.
Array: 38 9 38 37 155 197 65