Implemented O(nlogn) algorithm