-2

Is my algorithm faster then php sort() ?

algo:

        $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;
           }   
        }
        echo "<pre>";
        print_r($a);
        echo "</pre>";

compare with php sort() ... let me know your results as i have bad internet...

15
  • No it's not. This is not a place where people will compare your code to native PHP methods and give you results. Commented Aug 4, 2020 at 21:02
  • 1
    Why is $i an array? You never use anything other than $i[0]. Commented Aug 4, 2020 at 21:03
  • Of course, interpreted PHP code is always faster than optimized and compiled C binary. Commented Aug 4, 2020 at 21:03
  • 1
    Your algorithm looks like bubble sort. Commented Aug 4, 2020 at 21:04
  • 1
    @alin100 Try sorting an array with a million elements and see how they compare. Commented Aug 4, 2020 at 21:05

1 Answer 1

3

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;
    }   
}
Sign up to request clarification or add additional context in comments.

4 Comments

thank you for seeing that i changed it ...
in bubble sort en.wikipedia.org/wiki/Bubble_sort i noticed that it does not reset once you make switch of 2 value,it goes to the end of array ... in my code when you switch / flip values , it goes back to 0 and starts over ... it's a variation of bubble sort ...
That probably makes your algorithm worse, since there' no need to go back to the beginning.
who knows we may find a use for it one day :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.