greedy sort algorithm with P class