Internally speaking, which algorithm(s) does PHP use to implement the various sort functions it offers? It seems like the usort variants might use a different algorithm than the built in sorts, but I wanted to know.
Where would I even find this information?
Thanks!
According to Wikipedia "Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order.
Quicksort. Quicksort is one of the most efficient sorting algorithms, and this makes of it one of the most used as well. The first thing to do is to select a pivot number, this number will separate the data, on its left are the numbers smaller than it and the greater numbers on the right.
The Array#sort method in Ruby uses the venerable Quicksort algorithm. In its best case, Quicksort has time complexity O(n log n), but in cases where the data to be sorted is already ordered, the complexity can grow to O(n2).
Approach: 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.
You could find the information by looking at the php manual. http://php.net/sort says PHP uses an implementation of Quicksort. Failing that, you could always trudge through the PHP source code itself.
For sorting, PHP uses an implementation of quicksort that can be found in Zend/zend_sort.c
, which takes a comparison function and an array of elements. The default comparison function for sort()
is defined in ext/standard/array.c
and is called php_array_data_compare()
. So basically, it's the same algorithm for all sorting functions, except that they take different comparison functions.
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