是否可以通过自定义编写的 php 代码查看使用 usort 对数组进行排序的阶段?
Is it possible to see the stages of sorting an array with usort with a custom written php code?
可以说任何数组,但它只能应用于这段代码。根据这里的信息,我知道如果数组中有 6-15 个元素,则使用的排序算法将是插入排序,对于其他数量的元素,它将是快速排序:
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);
?>
人们一直在说我想太多了,这不是必需的,但是查看数组排序的每个阶段将是算法工作原理的最佳表示(从中弄清楚这一点并不容易我可以用 echo 或类似的东西输出的 $a-$b 对)。 var_dump 不会显示排序数组的阶段,它总是相同的。
同样,这是本题的唯一目标——实现查看排序(任意/一个)数组阶段的访问。
有人提出了这样的建议,但我还没弄清楚,这可能不是一件可行的事情:
"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."
谢谢。
不,这不可能。
在 usort 中创建了输入数组的副本,因此您将无法通过 PHP 代码观察它在做什么。
/* Copy array, so the in-place modifications will not be visible to the callback function */
arr = zend_array_dup(arr);
可以说任何数组,但它只能应用于这段代码。根据这里的信息,我知道如果数组中有 6-15 个元素,则使用的排序算法将是插入排序,对于其他数量的元素,它将是快速排序:
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);
?>
人们一直在说我想太多了,这不是必需的,但是查看数组排序的每个阶段将是算法工作原理的最佳表示(从中弄清楚这一点并不容易我可以用 echo 或类似的东西输出的 $a-$b 对)。 var_dump 不会显示排序数组的阶段,它总是相同的。
同样,这是本题的唯一目标——实现查看排序(任意/一个)数组阶段的访问。
有人提出了这样的建议,但我还没弄清楚,这可能不是一件可行的事情:
"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."
谢谢。
不,这不可能。
在 usort 中创建了输入数组的副本,因此您将无法通过 PHP 代码观察它在做什么。
/* Copy array, so the in-place modifications will not be visible to the callback function */
arr = zend_array_dup(arr);