this algorithm seems to keep order for any scenario