Sorting by hand
In lesson 17 a single word did the sorting: sort. But how does Ruby do it? A computer can't see at a glance, the way you can, which card is the smallest. It can only compare two things at a time and move them around. So let's sort by hand for once, step by step – with number cards on a table.
The first method does it the way you would: find the smallest card on the table, put it in your row, and repeat with the rest until the table is empty. It is called selection sort. delete_at(i) takes the card at position i off the table:
table = [5, 2, 8, 1, 9, 3]
row = []
until table.empty?
smallest = table.min
row << smallest
table.delete_at(table.index(smallest))
end
rowStep through the cell with ⏯: each round the table gets one card shorter and the row one card longer. (Why not simply delete(smallest)? It would take away every card with that value – of two equal cards, one would get lost.)
That was cheating a little, though: min did the real work, and min has to compare card after card too. By hand, a sorting method has only two tools: compare two cards and swap two cards. For swapping you don't need a helper variable as in lesson 3: a, b = b, a assigns both at once. Here is the same method inside the list itself: for every position i, find the smallest card from i on and swap it to the front. A counter counts the comparisons:
def selection_sort(list)
cards = list.dup
comparisons = 0
(0...cards.size).each do |i|
smallest = i
(i + 1...cards.size).each do |j|
comparisons += 1
smallest = j if cards[j] < cards[smallest]
end
cards[i], cards[smallest] = cards[smallest], cards[i]
end
puts "#{cards.size} cards: #{comparisons} comparisons"
cards
end
selection_sort([5, 2, 8, 1, 9, 3])15 comparisons for 6 cards: the first position takes 5 comparisons, the second 4, then 3, 2 and 1 – 15 in all.
The most famous method is bubble sort: walk along the row and compare two neighbours at a time. If they are the wrong way round, swap them. After one pass the largest number has bubbled up to the very end, the way a bubble rises in water. Repeat the passes until one gets by without a swap:
numbers = [5, 2, 8, 1, 9, 3]
swapped = true
while swapped
swapped = false
(0...numbers.size - 1).each do |i|
if numbers[i] > numbers[i + 1]
numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]
swapped = true
end
end
p numbers
endAfter the first pass the 9 is at the back, after the second the 8 sits in front of it; the fourth pass swaps nothing, and the loop stops. Bubble sort is simple but slow – it only ever moves a card one place at a time.
You know the third method from card games: insertion sort. You pick up one card after the other and slip each one into the right place in your hand – in front of the first card that is bigger. Two tools for it: index with a block finds the position of the first card for which the block is true (or nil if none is), and insert slips a card in at a position, the others move along to the right:
hand = [2, 5, 8]
p hand.index { |c| c > 3 } # the first card bigger than 3
p hand.index { |c| c > 9 } # no card is bigger than 9
hand.insert(1, 3) # the 3 at position 1You will write the whole method yourself at the end. First the most important question: how much work is sorting? Let's count the comparisons of selection_sort for 8, 16 and 32 cards – shuffle from lesson 10 mixes them up:
[8, 16, 32].each do |n|
selection_sort((1..n).to_a.shuffle)
end28, 120, 496: twice as many cards make four times as much work. In general it is n · (n - 1) / 2 comparisons – that grows like n². For 1000 cards that is almost half a million, for a million cards 500 billion. Bubble sort and insertion sort play in the same league.
A trick makes it faster: two piles that are already sorted are easy to merge into one. Look at the top card of both piles, take the smaller one, repeat. shift takes the first card out of an array:
def merge_piles(left, right)
pile = []
until left.empty? || right.empty?
if left.first <= right.first
pile << left.shift
else
pile << right.shift
end
end
pile + left + right
end
merge_piles([1, 4, 8], [2, 3, 9])As soon as one pile is empty, the rest of the other simply goes behind – left + right, since one of the two is empty anyway. And where do the sorted piles come from? From the recursion of lesson 30: split the cards into two halves, sort each half the same way and merge them. The base case: a single card (or none) is sorted already. That is merge sort. first(middle) takes the first half, drop(middle) leaves it out and gives the rest:
def merge_sort(list)
return list if list.size <= 1
middle = list.size / 2
left = merge_sort(list.first(middle))
right = merge_sort(list.drop(middle))
merge_piles(left, right)
end
merge_sort([5, 2, 8, 1, 9, 3, 7, 4])8 cards are halved three times until only single cards are left, and on every level each card is merged once: fewer than 8 · 3 = 24 comparisons instead of 28. With 32 cards it is fewer than 32 · 5 = 160 instead of 496, with a million about 20 million instead of 500 billion. And Ruby's own sort? Give it a block and Ruby calls it for every comparison – so you can count along:
[8, 16, 32].each do |n|
comparisons = 0
(1..n).to_a.shuffle.sort { |a, b| comparisons += 1; a <=> b }
puts "#{n} cards: #{comparisons} comparisons"
endAbout 15, 50 and 125 – a few more or fewer depending on the shuffle, but far below 28, 120 and 496, and about as many as merge sort needs. Ruby's sort splits the work just as cleverly, and on top of that it is written in C, which runs much faster than Ruby code. The rule of thumb: in real programs, always use sort. You sort by hand to understand how it works – and because the question “how many steps does this take?” matters for every program.
insertion_sort(list): take the cards of list into your hand one after the other and slip each one in front of the first card that is bigger – if there is none, it goes at the end. Without sort, sort_by, min and max! It must work with duplicate cards and with an empty list too.# def insertion_sort(list)
# hand = []
# ... # slip each card of list in front of the first bigger one in hand
# hand
# end
# insertion_sort([5, 2, 8, 1, 9, 3])
partition does that in one go: [5, 2, 8, 1].partition { |c| c < 4 } gives [[2, 1], [5, 8]]. Sort both piles with quicksort and put them together: small + [pivot] + big. Write quicksort(list) – again without sort, min and max.# def quicksort(list)
# return list if list.size <= 1
# pivot = list.first
# ... # split the rest: smaller than pivot, and the others
# ... # sort both piles, join them with [pivot] in the middle
# end
# quicksort([5, 2, 8, 1, 9, 3, 7, 4])