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 zero inversions is sorted.

Partially ordered arrays. Why does insertion sort take linear time for partially sorted arrays?

Recommended Problems

C level

  1. We would like to sort playing cards from a deck. Associated with each card is a rank (2 to 14) 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 Card class is implemented in Java as follows. Complete the compareTo() method.

    public class Card implements Comparable {
        private final int suit;  // suit (CLUBS = 1, DIAMONDS = 2, HEARTS = 3, SPADES = 4)
        private final int rank;  // rank (DUECE = 2, JACK = 11, QUEEN = 12, KING = 13, ACE = 14)
    
        public Card(int suit, int rank) {
            if (suit < 1 || suit > 4)
                throw new IllegalArgumentException("Invalid suit");
            if (rank < 2 || rank > 14)
                throw new IllegalArgumentException("Invalid rank");
            this.suit = suit;
            this.rank = rank;
        }
    
        // COMPLETE THE FOLLOWING METHOD
        public int compareTo(Card that) {
    
    
    
        }
    }
                  

  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. Fall 2012 midterm, #8
  4. 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()?
    Answers

A level

  1. Textbook 2.1.28