Exercises: Sorting
These exercises review the whole sorting chapter. They use the versions of the algorithms given in the lessons (for example, the bubble sort of the lesson moves the smallest elements to the left, scanning from right to left). Try each exercise before reading its solution: the solutions are grouped at the end of the page.
The sorting problem
2.1. Is it sorted correctly? A student checks his sorting method with a test that only verifies that the output is in ascending order. Give a wrong "sorting" method that passes this test for every input. What else must the test check?
2.2. Stability. For each algorithm, say whether it is stable as written in the lessons: bubble sort, insertion sort, selection sort, Quicksort, Mergesort. For one of the unstable ones, give a small array that shows it.
2.3. Sorting by two keys. A list of students must be sorted by grade, and students with the same grade must appear in alphabetical order. You have a stable sorting method that sorts by any single field. In which order should you sort, by name first or by grade first? Why?
Simple algorithms
2.4. Inversions. How many inversions does the array 4 7 1 6 2 have? How many swaps will bubble sort perform on it? And insertion sort, how many element shifts?
2.5. Rabbits and turtles. Apply the bubble sort with sentinel of the lesson (passes from right to left, stopping when a pass makes no swap) to 2 3 4 5 6 1 and to 6 1 2 3 4 5. How many passes does each one need? Explain the difference, and say which elements are the "turtles" for this version of the algorithm.
2.6. Insertion sort and nearly sorted data. Prove that the number of comparisons made by insertion sort is at least and at most , where is the number of inversions of the input. Deduce the cost of insertion sort on an array where every element is at most positions away from its final position.
2.7. Few swaps. How many swaps does selection sort perform on an array in descending order, n n-1 ... 2 1? (Try and by hand.) Why is it not ?
Quicksort
2.8. Limiting the stack. In the worst case, the recursive Quicksort of the lesson nests about calls, which can cause a StackOverflowError. Modify it so that the stack depth is in every case, without changing the partition.
2.9. Pivot choices. For each strategy, describe an input of elements that makes Quicksort quadratic, or explain why no simple input does: (a) the first element as pivot; (b) the central element as pivot; (c) a random element as pivot.
Merging
2.10. Merging cost. How many comparisons are needed to merge two sorted lists of sizes and , in the best and in the worst case? Give an example of each with and .
2.11. Merging many lists. You have sorted lists with elements in total. Describe an algorithm that merges them into one sorted list in time.
2.12. Top-k. A stream delivers numbers, one at a time, and you must output the 10 largest. You cannot store the whole stream. What structure would you use, and what is the cost?
Limits and choices
2.13. Sorting five elements. What is the minimum number of comparisons that any comparison-based algorithm needs, in the worst case, to sort 5 elements? Is that bound achievable?
2.14. Choosing. Which sorting algorithm would you choose in each situation, and why?
- (a) A large array that is already sorted except for a few elements appended at the end.
- (b) A server that must guarantee in every case, even for inputs chosen by an attacker, and has memory to spare.
- (c) A list of
Employeeobjects that must keep the previous order of employees with equal salaries. - (d) 500 GB of records on disk, on a computer with 16 GB of memory.
Solutions
2.1. A method that writes zeros in every position, or simply returns [1, 2, ..., n], passes the test. A correct test must also check that the output is a permutation of the input: the same elements, the same number of times. A simple way is to sort a copy with a trusted method (Arrays.sort) and compare the arrays; another is to compare the frequency of each value before and after.
2.2. Stable: bubble sort, insertion sort and Mergesort (when, in the merge, equal elements are taken from the left half first). Unstable: selection sort and Quicksort. Example for selection sort: 2a 2b 1. The first step swaps the minimum 1 with the element in position 0, 2a, giving 1 2b 2a: the two 2s have changed their relative order.
2.3. By name first, then by grade. The second sort decides the main order (grade). Because it is stable, students with the same grade keep the order they had after the first sort, which was alphabetical. Sorting in the other order would leave the list sorted by name, with grades mixed. This is how spreadsheets and many databases sort by several columns.
2.4. The inversions are the pairs out of order: (4,1), (4,2), (7,1), (7,6), (7,2), (6,2), so 6 inversions. Every swap of adjacent elements removes exactly one inversion, so bubble sort performs 6 swaps, and insertion sort performs 6 shifts. Running the bubble sort with sentinel on this array confirms it: 6 swaps, in 4 passes and 10 comparisons.
2.5. 2 3 4 5 6 1 needs 2 passes: in the first one, the 1 travels all the way from the end to the front, and the second pass finds nothing to swap. 6 1 2 3 4 5 needs 5 passes (with 15 comparisons), the maximum for : the 6 can only move one position to the right per pass, because each pass carries small elements to the left. For this version of the algorithm, the turtles are large elements near the beginning; the rabbits are small elements near the end. (The version that scans from left to right has the opposite behavior. Bidirectional bubble sort alternates both directions to move both kinds quickly.)
2.6. Each comparison key < elements[j] either succeeds, and then key passes over an element larger than itself (removing one inversion), or fails, and then the insertion of that key ends. So there are exactly successful comparisons plus at most one failed comparison for each of the insertions: between and comparisons. (On random arrays of 20 elements we counted, for example, 103 comparisons with , inside the range 87 to 106.) If every element is at most positions away from its final place, an element that is larger than and stands to its left must be among the positions just before (otherwise one of the two would be more than positions away from its place). So each element forms fewer than inversions with the elements to its left, , and the cost is : linear for constant . This is why insertion sort is used for nearly sorted data.
2.7. swaps: 3 for and also 3 for . The first step swaps the first and last elements (n and 1), which puts both in their final positions. The same happens with the second and the next-to-last, and so on, so after swaps every remaining minimum is already in place and the algorithm (which skips the swap when i == posMin) swaps nothing else.
2.8. Recurse only on the smaller part and handle the larger part with a loop:
private void quickSortIterative(int[] elements, int left, int right) {
while (right - left >= 3) {
int p = partition(elements, left, right); // the partition of the lesson
if (p - left < right - p) { // left part is smaller
quickSortIterative(elements, left, p - 1);
left = p + 1; // continue with the right part
} else {
quickSortIterative(elements, p + 1, right);
right = p - 1; // continue with the left part
}
}
sortSmall(elements, left, right); // 3 elements or fewer
}
Here partition is the partition loop of the lesson, moved to a method that returns the final position of the pivot, and sortSmall is the medianOfThree call, which already sorts ranges of 3 elements or fewer. Every recursive call receives at most half of the current range, so there can be at most nested calls. The time in the worst case is still ; only the memory is protected.
2.9.
- (a) An array that is already sorted (or in reverse order): every partition leaves one part empty.
- (b) There are inputs that defeat it, but they are not "natural": they must be built on purpose, placing the smallest (or largest) remaining element in the center of each subarray. Sorted and reversed arrays, which defeat (a), are the best case for (b).
- (c) No fixed input is bad for a random pivot. The expected time is for every input; quadratic time is possible only through extremely unlikely random choices. This is the main argument for randomized pivots: they protect against inputs crafted by an adversary.
2.10. Each comparison places one element in the output, and the merge stops comparing when one of the lists is empty. Best case: every element of the shorter list is smaller than every element of the longer one, comparisons; for example 1 2 3 and 4 5 6 7 need 3. Worst case: both lists are exhausted at the very end, comparisons; for example 2 4 6 and 1 3 5 7 need 6.
2.11. Put the first element of each list in a priority queue (Java's PriorityQueue), together with the index of its list. Repeatedly extract the minimum, append it to the output, and insert the next element from the same list. The queue never has more than elements, and in a PriorityQueue each insertion or extraction costs : in total. Merging the lists two by two in a balanced way (as Mergesort does) gives the same bound.
2.12. A priority queue of size 10 that gives the minimum (Java's PriorityQueue). For each new number, if the queue has fewer than 10 elements, insert it; otherwise, if the number is larger than the minimum of the queue, remove the minimum and insert the number. At the end, the queue holds the 10 largest. Each step costs with , so the total is , practically linear, with memory.
2.13. There are possible orders, and each comparison has two outcomes, so at least comparisons are needed in the worst case. The bound is achievable: there is an algorithm (merge insertion, by Ford and Johnson) that sorts any 5 elements with exactly 7 comparisons. Mergesort needs 8 in its worst case for .
2.14.
- (a) Insertion sort, or the library's TimSort (
Arrays.sortfor objects,List.sort), which detects sorted runs. Both are close to linear when few elements are out of place. - (b) Mergesort: in every case, whatever the input; its extra memory is not a problem here. Quicksort is not a good choice, because an attacker can build inputs that make it quadratic.
- (c) A stable algorithm: Mergesort, or the library's TimSort, which is stable. Quicksort would not respect the previous order.
- (d) External sorting: sort the data in chunks of about 16 GB in memory, write each sorted chunk to disk, and merge the chunks with a -way merge (exercise 2.11), reading and writing the disk sequentially.
Errors, suggestions and public questions open a form on GitHub, visible to everyone.