CS 119 Sorting Algorithms

Selection Sort

You will use three positions for stacks of cards: source stack, destination stack, and the discard stack.

Initially you should put all the cards, face down, on the source stack, with the other two positions empty. Now do the following steps repeatedly:

  1. Take the top card off the source stack and put it face-up on the destination stack.
  2. If that makes the source stack empty, you are done. The destination stack is in numerical order.
  3. Otherwise, do the following steps repeatedly until the source stack is empty:
    a. Take the top card off the source stack and compare it with the top of the destination stack.
    b. If the source card has a larger number,
        i. Take the card on top of the destination stack and put it face down on the discard stack.
        ii. Put the card you took from the source stack face up on the destination stack.
    c. Otherwise put the card from the source stack face down on the discard stack.
  4. Slide the discard stack over into the source position, and start again with step 1.
    1.  

Merge Sort

Lay out the cards face down in a long row. We will consider these to be the initial source "stacks" of cards, even though there is only one card per stack. The merge sorts works by progressively merging pairs of stacks so that there are fewer stacks but each is larger; at the end, there will be a single large stack of cards.

Repeat the following steps until there is a single stack of cards:

  1. Merge the first two face-down stacks of cards using Merge algorithm given below.
  2. As long as there are a least two face-down stacks, repeat the merging with the next two stacks.
  3. Flip each face-up stack over.
    1.  

Merging

You will have the two sorted stacks of cards to merge side by side, face down. You will be producing the result stack above the other two, face up.

Take the top card off of each source stack – one in your left hand and one in your right hand. Now do the following repeatedly, until all the cards are on the destination stack:

  1. Compare the two cards you are holding.
  2. Place the one with the larger number on it onto the destination stack, face-up.
  3. With the hand you just emptied, pick up the next card from the corresponding source stack and go back to step 1. If there is no next card in the empty hand’s stack because that stack is empty, put the other card you are holding on the destination stack face-up and continue flipping the rest of the cards over onto the destination stack.
    1.