this is quadratic. Can't you create a Comparator and then call something like Collections.sort?