Minor refactoring of sortByDepth