This was the first version I wrote.  It's O(n^2), albeit with an OK constant.