better algorithm, ordered output