### ELEMENTARY SORTS STUDY GUIDE

Selection sort. Be able to selection sort an array. How many compares does it use? How many exchanges?

Insertion sort. Be able to insertion sort an array. How many compares does it use in the best and worst case? How many exchanges in the best and worst case?

Inversions. The number of pairs of elements in a sequence that are out of order. An array with no inversions is ordered.

Partially ordered arrays. Why is insertion sort linear for partially sorted arrays?

Shuffling. Can use sorting to shuffle in n log n time by assigning each value an arbitrary unique value between 0 and 1. Can shuffle in linear time using Knuth shuffle.

### Recommended Problems

#### C level

1. We would like to sort playing cards from a deck. Associated with each card is a denomination (1 to 13) and a suit
(CLUBS < DIAMONDS < HEARTS < SPADES). A card c1 is considered less than a card c2 if either of the following is true:
- the suit of c1 is less than the suit of c2, or
- c1 and c2 are of the same suit, but the denomination of c1 is less than the denomination of c2. The Card class is implemented in Java as follows. Complete the compareTo() function, implementing the ordering described on the previous page, and assuming that the argument is not null.
```  public class Card implements Comparable {
// Comparators by suit and by denomination
public static final Comparator SUIT_ORDER = new SuitOrder();
public static final Comparator DENOM_ORDER = new DenomOrder();
// Suit of the card (CLUBS = 1, DIAMONDS = 2, HEARTS = 3, SPADES = 4)
private final int suit;

// Denomination of the card
private final int denom;
public Card(int suit, int denom) {
if (suit < 1 || suit > 4)
throw new IllegalArgumentException("Invalid suit");
if (denom < 1 || denom > 13)
throw new IllegalArgumentException("Invalid denomination");
this.suit = suit;
this.denom = denom;
}
// COMPLETE THE FOLLOWING FUNCTION
public int compareTo(Card that) {

}

// Compare cards according to the suit only
private static class SuitOrder implements Comparator {
// Implementation not shown
}
// Compare cards according to the denomination only
private static class DenomOrder implements Comparator {
// Implementation not shown
}
}
```

2. Give a worst-case and best-case family of inputs for insertion sort and selection sort.

#### B level

1. Textbook 2.1.2
2. Textbook 2.1.6, 2.1.7
3. If you run your BinarySearchDeluxe on a sorted array with N items but only 3 distinct keys, what is the order of growth of the expected running time for a call to firstIndexOf()?