cherrypicked qsort patch on 3.1

Hoping to get this into 3.1.