In the worst case, qsort() can take O(n**2) time and consume O(n) stack
space. Use mergesort instead.
Suggested by: Ryan Stone <rstone@freebsd.org>
Further fix a bug in the compare routine when comparing 32-bit integers we need to use a 64-bit variable.