Algorithms and OOD (CSC 207 2014S) : Outlines

# Outline 25: An Introduction to Sorting

Held: Monday, 3 March 2014

Back to Outline 24 - Java Generics. On to Outline 26 - Quadratic Sorts.

Summary

We consider the well-known problem of sorting. Along the way, we consider some issues in testing and object-oriented design.

Related Pages

Overview

• The problem of sorting.
• An object-oriented approach.
• Testing our sorting algorithm.

• Have fun with Earnest!
• Reading for Tuesday: Sorting Basics
• I will take volunteers for note takers for Tuesday, Wednesday, and Friday. Extra credit for note taking.
• Homework 5 is due March 5. I'll take questions.
• Extra credit:
• Convocation, noon, Wednesday.
• Presentations on Grinnell institutional image, noon on Thursday or Friday.

## The problem of sorting

• Goal: Given a collection of values, put them in order.
• How do you decide what order?
• Sometimes we use the natural ordering.
• Sometimes we use a comparator.

## An object-oriented approach

• We'll build a sorter interface.
• Will the individual objects ever need more than one copy? Probably not. We'll see how to handle that issue later.
• The basic method: Sort an array of T's using an appropriate comparator.
• I'll ask you to fill in the blanks (preconditions, postconditions, etc.)

## Testing sorters

• How do we test a sorter?
• Three basic approaches:
• Systematically generate a lot of samples and see that it works on all of them
• Randomly generate a lot of samples and see that it works on all of them
• Perhaps do a few special cases
• How do we know that a sort method has succeeded?
• The result is in order
• The result is a permutation of the original array
• We can check these by writing `inOrder` and `isPermutation` predicates, but those are a pain.
• A better strategy:
• Make a copy.
• Permute the copy.
• Sort the permuted copy.
• Compare to the original array.
• For the random samples approach, we just need a "randomly permute" method.
• For the systematic approach, we might want to make all permutations. But how?

## Sam's favorite permutation algorithm

Copyright (c) 2013-14 Samuel A. Rebelsky.

This work is licensed under a Creative Commons Attribution 3.0 Unported License. To view a copy of this license, visit `http://creativecommons.org/licenses/by/3.0/` or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.