Sort an array by keys using a user-defined comparison function