Code from Algorithms by Sedgewick and Wayne.