Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What sort algorithm does PHP use?

Tags:

algorithm

php

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!

like image 853
Joe Mastey Avatar asked Jul 02 '10 13:07

Joe Mastey


People also ask

What is bubble sort in PHP?

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.

Which sort algorithm is most commonly used?

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.

What algorithm does Ruby sort use?

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).

How do you sort an object in PHP?

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.


2 Answers

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.

like image 154
Timothy Avatar answered Oct 04 '22 18:10

Timothy


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.

like image 35
Daniel Egeberg Avatar answered Oct 04 '22 20:10

Daniel Egeberg