You are on page 1of 2

Sorting algorithms

Most people are really inefficient at sorting. If they're sorting cards, for ins
tance, they use either insertion sort (taking the next card, then going back thr
ough already sorted cards to insert it before a higher value) or selection sort
(finding the smallest card in an unsorted set of cards, and then pushing it back
to the beginning of a list of sorted cards).
What they don't know is that these are together the worst ways to sort a set of
cards. If you have n cards, selection sort will take n2 operations to pull off i
n all cases. Insertion sort similarly takes n2 operations to pull off in most ca
ses, only in the best possible cases giving you n operations. For a pack of 100
cards, you have to do 100,000 operations on average!
Computer scientists (just applied mathematicians, really) have spent decades res
earching the best possible sorting algorithms. Their recommendation? Use bucket
sort!
Divide your cards into 'buckets'. How you want to do this is upto you - you can
choose to say that all cards belonging to a common house should belong in the sa
me bucket, or all cards with the same number should belong in a bucket. The more
buckets you have, the better you'll be.
Sort all the cards in a bucket.
Then just bring them all together.
Tada! Bucket sort, on average, only takes about O(n) operations - it's a linear
operation that'll take much less time than other methods (see Big-O Algorithm Co
mplexity Cheat Sheet). Postmen, I'm told, make use of this trick when sorting ma
il - they divide letters into domestic and international, then by class, and so
on. Now you can spend more time tending to things other than sorting presents, c
ards, and mail!
(and yes, this is math).
Compute Squares Quickly
Notice that, for any two perfect squares n,m,
n2-m2=(n-m)*(n+m)
Say you want to compute 192. Well, from this trick, you know that
192-92=(19-9)(19+9)=280
so that 192=280+92=280+81=361.
This trick works very well if you know how to multiply quickly.
Exponentiation by Squaring
Need to find a large exponent of a large number quickly? Use the following:

The trick is simple: if n is even, compute the square, then multiply the square
out n/2 times. For n odd, do something similar. A lot of software makes use of t
his trick to reduce computation time, as it's much faster than multiplying a num
ber by itself over and over again. See How is exponentiation by squaring faster?
for a really good demonstration of its power.
Truncated MacLaurin Series for Square Roots

A very rough way to calculate square roots:


xv a+x-a22a
where a2 is the closest perfect square that comes before x. This formula is obta
ined by computing the Taylor series about the nearest perfect square - for even
better precision, feel free to extend it to third or fourth degree.
Simple demonstration: 17--v 4+17-1624=4.125. In reality, 17--v=4.123105....

You might also like