Sort ranges before checking

Idea and implementation by PavelVolkovitskij