Added test.
Rewrote to be bounded by O(n^2).