Is this algorithm faster then php sort()?
one text
Solution:
As pointed out in What sort algorithm does PHP use?, the built-in sorting algorithm is Quicksort. The average performance of Quicksort is O(n log n).
Your algorithm is similar to Bubble Sort. Its average performance is O(n2). But since your code goes back to the beginning after each swap, which is unnecessary, it's even worse than bubble sort.
For large arrays, Quicksort will be significantly faster than Bubble Sort.
Also, the sort()
function is implemented in C code, which is compiled to machine code. Using a sorting algorithm written in PHP will have additional overhead of the PHP interpreter.
You also have a number of unnecesary arrays $i
and $z
, which should just be ordinary variables.
$a = array(0,3,4,2,7,6,6,8,6,1);
$z = count($a)-1;
for($i = 0;$i < $z; $i++){
if($a[$i] > $a[$i+1]){
$temp = $a[$i];
$a[$i] = $a[$i+1];
$a[$i+1] = $temp;
$i = -1;
}
}
Source