I want to sort files by modification time ascending and descending.
According to this answer It looks like this can best be achieved defining a sort callback function and using usort/uasort.
However because of the nature of my application I am likely to run into some worst case scenarios for some sort algorithms (for example almost reverse-ordered input sequence).
Because every comparison uses two file system accesses which are partly on network drives, the number of comparisons is critical and must be minimized. Other sorts of iterations can be more.
So what sort algorithms do PHP's array sort functions utilise? Quicksort? Multisort? Is there any way I can configure this?
Should I perhaps shuffle the array before sorting?
Or do I need to write my own implementation?
Do you know some good libraries that provide sort functions with configurable algorithms?
What algorithm or ways to solve this problem of minimizing comparisons would you recommend?
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.
Quicksort is probably more effective for datasets that fit in memory. For larger data sets it proves to be inefficient so algorithms like merge sort are preferred in that case. Quick Sort is an in-place sort (i.e. it doesn't require any extra storage) so it is appropriate to use it for arrays.
The sort() function is an inbuilt function in PHP and is used to sort an array in ascending order i.e, smaller to greater. It sorts the actual array and hence changes are reflected in the original array itself. The function provides us with 6 sorting types, according to which the array can be sorted.
At php.net/sort
I found this:
Note: Like most PHP sorting functions, sort() uses an implementation of » Quicksort.
I believe that it uses a randomized quicksort, so there is no need for shuffling the array.
I did some tests and PHP's quicksort is not randomized, so shuffle your input array!!
I did a few searches using PHP OpenGrok, and just based on some glancing at function names and skimming code, it looks like usort is implemented with quicksort.
To minimize the file system calls, make them once for each item in your array, and store the results in another array. Use that second array in your comparator function instead of making the calls again.
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