First attempt, O(nlogn)