Algorithms and OOD (CSC 207 2014F) : Labs

# Laboratory: Quicksort

Summary: We explore the construction of Quicksort.

Prerequisite Knowledge: The general structure of Quicksort. Arrays. Loop invariants.

## Preparation

If you have not already done so, fork and clone the repository at https://github.com/Grinnell-CSC207/sorting

## Exercises

a. Explain why there are two sorting procedures in `Quicksorter.java`, one called `sorti` and one called `qsort`.

b. The Quicksort algorithm says (approximately): “Divide the collection into small values and large values, sort the two subcollections, and join them back together.” How is each aspect of that algorithm represented in `qsort`?

c. In your own words, explain what value `partition` returns.

### Exercise 2: Picking a Random Pivot

Quicksort requires you to pick an element of the collection as a “pivot” to use to identify small (<= pivot) and large (> pivot) elements. Write a procedure that, given an array, a lower bound, and an upper bound, and a comparator, picks a random pivot in the given range. (You probably won't need the comparator, but we include it because we'll use it later.)

### Exercise 3: A Loop Invariant

Sketch a loop invariant for partition. (You may want to refer to the reading for a suggestion. If you use that suggestion, you should make sure that you understand what's going on.

### Exercise 4: Implement Partition

You should now be ready to implement the partition method. Do so.

### Exercise 5: Tests and Experiments

Conduct a few tests or experiments to determine whether your partition and sorting methods work correctly.

## For Those With Extra Time

### Extra 1: Choosing a Pivot, Revisited

I've been told that we can significantly improve the behavior of Quicksort by randomly picking three candidates for the pivot, and using the median of the three. Rewrite your procedure to pick a Pivot to use that strategy.

### Extra 2: Does the Pivot Matter

I've also been told that the middle value in a subarray is an ideal pivot, since it works well for arrays that are already sorted and already backwards sorted, and is no more or less good than a random element for other arrays.

Design and conduct an experiment that lets you check that assertion.