 ## UkSort() PHP function

Started by Crevand, Oct 20, 2022, 04:32 AM

#### Crevand Good day for all.
I am analyzing the work of the uksort() function, I ask you to comment on whether I understood its work correctly.

Using the example of this code:

`function my_sort(\$x, \$y){ if (\$x == \$y) return 0; return (\$x > \$y) ? 1 : -1; } \$names = array( "10" => "javascript", "20" => "php", "60" => "vbscript", "40" => "jsp" ); uksort(\$names, "my_sort");echo "<pre>"; print_r (\$names); echo "</pre>";`
the result will be:
 => javascript
 => php
 => jsp
 => vbscript

As I understand it: The keys are compared and immediately moved to the right place in this way:
first 10 with 20 - the result is -1, respectively, the key 10 moves to the left to the left end (or rather the beginning)
then 10 with 60 - the result is -1, respectively, the key 10 moves to the left to the end, i.e. in this case it remains in place
then 10 with 40 - the result -1, respectively, the key 10 moves to the left to the end, i.e. in this case it remains in place
then 20 with 60 - the result -1, respectively, the key 20 moves to the left to the key 10
then 20 with 40 - the result -1, respectively, the key 20 moves to the left to the key 10, i.e. in in this case, it remains in place

Question: Did I understand the sorting algorithm correctly?
•

#### richardBranson

#1
Of course, it is possible to sort this way, but very slowly (O(n^2)). Most likely, something like Hoare's quick sort (O(n*log(n))) is implemented inside, but this is not accurate.
If it's very interesting, then the php source code is open, you can search there.

This is made easier in modern php - with the help of the spaceship operator. And you don't have to create a function, the arrow is enough. But here it is not necessary, ksort will make the same comparison.
And it makes no sense to take numeric keys in quotation marks, php automatically converts them to numbers https://www.php.net/manual/en/language.types.array.php
•