简体   繁体   中英

Is it possible to see the stages of sorting an array with usort with a custom written php code?

Lets say any array but it can be applying only to this piece of code. Based on the info from here I know that if there is 6-15 elements in an array the sorting algorithm used would be Insertion Sort and for other number of elements it would be the Quicksort:

https://github.com/php/php-src/blob/eac0bf11e4e97916e9688b18e6d62572e12e129f/Zend/zend_sort.c#L176

<?php
function testing($a,$b){
    if ($a < $b ){
        return -1;
    }
    elseif ($a > $b){
        return 1;
    }
    //else {
        //return 0;
    //}
}

$array = array(1,3,2,4,5);
usort($array, "testing");
var_dump($array);
?>

People have been saying that I am overthinking this and that this is not needed, but seeing every stage of sorting the array would be the best representation of how the algorithm works (it is not that easy to figure this out from the $a-$b pairs that I can output with echo or something like that). var_dump will not show me the stages of sorting an array, it will be always the same.

Again, this is the only goal of this question - achieve the access to viewing the stages of sorting (any / an) array.

Somebody has suggested something like this but I have not been able to figure this out, it may not be a doable thing:

"You could try with an anonymous function referencing the array (usort($arr, function ($a, $b) use ($arr) { ... })) and output the array every step of the way too… I'm not sure whether the result would be reflected immediately or not though."

Thanks.

No, it isn't possible.

A copy of the input array is created in usort, so you won't be able to observe what it's doing via PHP code.

See in the PHP source code for usort :

/* Copy array, so the in-place modifications will not be visible to the callback function */
arr = zend_array_dup(arr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM