Fix bug on sorting algorithm on certain branches, closes #1580