At first, I'll give a link to code: http://ideone.com/6k8R6
On my Intel Core 2 Duo, PHP 5.4.6 result is:usort: 7.8763520717621
quicksort: 2.9220938682556
(usort
is slower than quicksort
)
But on Ideone result is:usort: 0.0313699245453
quicksort: 0.0621209144592
(usort
is faster than quicksort
)
I have also checked code at my friend's computer (Intel Core i5, PHP 5.4.4), and usort
was also faster.
My question is: why sometimes quicksort is faster than usort and sometimes usort is faster?
The usort() function in PHP sorts a given array by using a user-defined comparison function. This function is useful in case if we want to sort the array in a new manner. This function assigns new integral keys starting from zero to the elements present in the array and the old keys are lost.
PHP - Sort Functions For Arrayssort() - sort arrays in ascending order. rsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key.
The usort() function is an inbuilt function in PHP which is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field.
Answer: Use the PHP sort() and rsort() function.
Quicksort is considered one of the fastest sort algorithms on unsorted data, and the slowest on already sorted (or nearly sorted) data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With