finished the nlogn implementation