【问题标题】:How the usort() sorting algorithm works?usort() 排序算法是如何工作的?
【发布时间】:2017-09-27 18:50:19
【问题描述】:

我有一个 usort() 示例,并添加了一些 echo 语句来查看代码的工作原理:

<?php
function list_cmp($a, $b) {
    global $order;
    echo "\$a=$a, \$b=$b </br>";

    foreach ($order as $key => $value) {
        echo "\$value=$value </br>";
        if ($a == $value) {
            echo "\$a=\$value, returing 0. </br>";
            return 0;
        }
        if ($b == $value) {
            echo "\$b=\$value, returing 1. </br>";
            return 1;
        }
    }
}

$order[0] = 1;
$order[1] = 3;
$order[2] = 4;
$order[3] = 2;

$array[0] = 2;
$array[1] = 1;
$array[2] = 3;
$array[3] = 4;
$array[4] = 2;
array[5] = 1;
$array[6] = 2;

usort($array, "list_cmp");
?>

代码的输出是这样的:

$a=2, $b=1 
$value=1 
$b=$value, returing 1. 
$a=2, $b=3 
$value=1 
$value=3 
$b=$value, returing 1. 
$a=1, $b=3 
$value=1 
$a=$value, returing 0. 
$a=2, $b=4 
$value=1 
$value=3 
$value=4 
$b=$value, returing 1. 
$a=3, $b=4 
$value=1 
$value=3 
$a=$value, returing 0. 
$a=2, $b=2 
$value=1 
$value=3 
$value=4 
$value=2 
$a=$value, returing 0. 
$a=2, $b=1 
$value=1 
$b=$value, returing 1. 
$a=2, $b=1 
$value=1 
$b=$value, returing 1. 
$a=4, $b=1 
$value=1 
$b=$value, returing 1. 
$a=3, $b=1 
$value=1 
$b=$value, returing 1. 
$a=1, $b=1 
$value=1 
$a=$value, returing 0. 
$a=2, $b=2 
$value=1 
$value=3 
$value=4 
$value=2 
$a=$value, returing 0. 

创建 12 个 $a-$b 对 - 2-1, 2-3, 1-3, 2-4, 3-4, 2-2, 2-1, 2-1 的机制是什么(还是一样?)、4-1、3-1、1-1、2-2。上面的代码返回 1,1,0,1,0,0,1,1,1,1,0,0。还有根据返回的值对数组进行排序的机制是什么?我试图了解 usort() 机制是如何工作的。

谢谢。

【问题讨论】:

  • sort() 使用快速排序,文档似乎暗示 PHP 中的大多数其他排序也使用相同的算法
  • 您的排序功能有问题。如果两个元素具有相同的排序值,它应该返回 0。如果第一个元素具有更高的排序值,那么它应该返回一个正值。如果第二个元素具有更高的排序值,那么它应该返回一个负值。

标签: php quicksort usort


【解决方案1】:
  1. 比较器的工作原理是什么?

我不确定这是否是问题的一部分,但要清楚比较器的工作原理: 您有一个由有序列表 $order 指定的顺序和一个特殊的 比较器回调 list_cmp,它(应该)返回参数

  • $a 小于 $breturn -1 或值 &lt; 0
  • $a 大于 $breturn 1 或值 &gt; 0
  • $a 等于 $b (return 0)

list_cmp 这样做是通过查找其 订单表 而不是检查是否

  • $a 的顺序更小(或相等),在这种情况下,循环会提前退出 return 0 或如果
  • $b 的顺序较小,在这种情况下循环会以 return 1 提前退出。

请注意,根据 PHP 文档,这是错误的,该文档声明它希望正/负/0 作为返回值。仅当您知道内部仅检查 comparator($a,$b) &gt; 0 时,这才是正确的,这意味着它仅检查 $b 是否小于或不等于 $a,这是一个比较 order of $a &lt;= order of $b。如果代码开始检查$a 是否小于或不等于$b,它很容易中断。

  1. 快速排序排序如何工作?

对于初学者,我假设您使用的是 PHP 7 或更高版本。在这种情况下,您遇到了一个特殊情况,即 6-15 个元素大小的数组。 PHP 7+ 似乎没有对短列表使用快速排序,而是使用插入排序变体(由于缓存/代码局部性等硬件相关的东西,这很可能更快)。您可以检查排序源代码 f.e.在Github PHP Mirror (as an example: PHP 7.0 Zend/Zend_sort.c Line 177-198)

代码分三步工作:

  1. 比较:比较相邻元素array[j]array[j+1],如果array[j] &lt;= array[j+1]继续,否则转到2。
  2. 查找插入点:现在如果是array[j] &gt; array[j+1],则向后扫描以找到array[x] &lt; array[j+1] &lt;= array[x+1] for x &lt; j 的点(显然只有在x 开始之前)
  3. 插入:将元素x+1 ... j 上移一个,使其变为x+2 ... j+1,并在x+1 位置插入前一个元素

如果您将该代码应用于配对(2-1、2-3、1-3、2-4、3-4、2-2、2-1、2-1、4-1、3- 1, 1-1, 2-2) 代码的作用显而易见。

-- [2,1],3,4,2,1,2 -> 1./2./3. compare [2,1], find and insert 1 before 2
-- 1,[2,3],4,2,1,2 -> 1./2. compare [2,3], find insert point for 3 (since order of 3 < order of 2)
-- [1,3],2,4,2,1,2 -> 3. compare [1,3], found insert point for 3 before 2
-- 1,3,[2,4],2,1,2 -> 1./2. compare [2,4], find insert point for 4 (since order of 4 < order of 2) 
-- 1,[3,4],2,2,1,2 -> 3. compare [3,4], found insert point for 4 before 2
-- 1,3,4,[2,2],1,2 -> 1. compare [2,2], skip
-- 1,3,4,2,[2,1],2 -> 1./2. compare [2,1], find insert point for 1
-- 1,3,4,[2,1],2,2 -> 2. compare [2,1], find insert point for 1
-- 1,3,[4,1],2,2,2 -> 2. compare [4,1], find insert point for 1
-- 1,[3,1],4,2,2,2 -> 2. compare [3,1], find insert point for 1
-- [1,1],3,4,2,2,2 -> 3. compare [1,1], fond insert point for 1 before 3
-- 1,1,3,4,2,[2,2] -> 1. compare [2,2], skip
-- sorted: 1,1,3,4,2,2,2

PS: 在这里,您已经看到,即使是简单的排序算法(22 行代码),通过其比较模式推导出其工作也是相当复杂的。 PHP 7 快速排序实现的代码行数大约是原来的 10 倍,并且有一些奇怪的优化(除了由于枢轴选择和递归而导致的正常疯狂之外)。

大多数时候最好忽略深入的实现细节,只将其减少到需要的东西。排序算法的典型问题是它是否稳定/不稳定并且在O(log n)O(n) 内存消耗下执行。有一些更简单的方法可以学习这些优化实现背后的核心算法,例如 Quicksort Dance 或任何其他可视化或带有示例的旧(电子)书或网页。

-- 已编辑

为插入排序添加了一个(坏的、未优化的、不安全的)php 实现,以另一个可视化的方式展示它的工作原理:

<?php

function my_usort($A, $comparator) {
  // Start .. End Positions
  $current_pos = 0;
  $last_pos = count($A)-1;
  // Outer Loop: each step checks that A[0] up to A[current_pos] is sorted. 
  // When the algorithm finishes we know that A[0] ... A[last_pos] is sorted
  while($current_pos < $last_pos) {
    echo "Sorted Subarray from \$A is " . json_encode(array_slice($A, 0, $current_pos+1)) . "<br>\n";
    echo "\$A looks like this now: " . json_encode($A) . 
    ", comparing [" . $A[$current_pos] . "," . $A[$current_pos +1] . "] (verify step)<br>\n";
    // "Verification Step"
    // At this point A[0] ... A[current_pos] is sorted.
    // Check A[current_pos] <= A[current_pos +1]
    if($comparator($A[$current_pos], $A[$current_pos +1]) > 0) {
      // nope, A[current_pos] > A[current_pos +1] (list_cmp/comparator returns value > 0)
      // "Insertion Step" start, find the correct position for A[current_pos+1] in the already
      // sorted list A[0] ... A[current_pos]
      $insert_point = $current_pos;
      // Swap the missmatching Neighbor pair
      echo "swapping: \$A[" . $insert_point . "] and \$A[" . ($insert_point+1) . "]<br>\n";
      $tmp = $A[$insert_point +1];
      $A[$insert_point +1] = $A[$insert_point];
      $A[$insert_point] = $tmp;
      $sorted_up_to_current_pos = false;
      // Inner Loop: find correct insertion point
      while($insert_point > 0 && !$sorted_up_to_current_pos) {
        echo "\$A looks like this now: " . json_encode($A) . 
        ", comparing [" . $A[$insert_point-1] . "," . $A[$insert_point] . "] (insertion step)<br>\n";
      // "Insertion Step", Swap the missmatching Neighbor pairs until A[0] ... A[current_pos] is sorted again
      if($comparator($A[$insert_point-1], $A[$insert_point]) > 0) {
          // Swap the missmatching Neighbor pair
          echo "swapping: \$A[" . ($insert_point-1) . "] and \$A[" . $insert_point . "]<br>\n";
          $tmp = $A[$insert_point];
          $A[$insert_point] = $A[$insert_point-1];
          $A[$insert_point-1] = $tmp;
          // goto new pair
          $insert_point = $insert_point -1;
        } else {
          // found correct spot, done
          $sorted_up_to_current_pos = true;
        }
      }
      $A[$insert_point] = $tmp;
      echo "\$A looks like this now: " . json_encode($A) . ", insertion done<br>\n";
    }
    $current_pos = $current_pos + 1;
  }
  echo "Sorted Array \$A is " . json_encode(array_slice($A, 0, $current_pos+1)) . "<br>\n";
}

function list_cmp($a, $b) {
  global $order;
  //echo "\$a=$a, \$b=$b </br>\n";

  foreach ($order as $key => $value) {
      //echo "\$value=$value </br>\n";
      if ($a == $value) {
          echo "\$a=\$value, returing 0. </br>\n";
          return 0;
      }
      if ($b == $value) {
          echo "\$b=\$value, returing 1. </br>\n";
          return 1;
      }
  }
}

$order[0] = 1;
$order[1] = 3;
$order[2] = 4;
$order[3] = 2;

$array[0] = 2;
$array[1] = 1;
$array[2] = 3;
$array[3] = 4;
$array[4] = 2;
$array[5] = 1;
$array[6] = 2;

my_usort($array, "list_cmp");

现在已完成输出,包含当前排序的数组,位置:

Sorted Subarray from $A is [2] 
$A looks like this now: [2,1,3,4,2,1,2], comparing [2,1] (verify step) 
$b=$value, returing 1.  
swapping: $A[0] and $A[1] 
$A looks like this now: [1,2,3,4,2,1,2], insertion done 
Sorted Subarray from $A is [1,2] 
$A looks like this now: [1,2,3,4,2,1,2], comparing [2,3] (verify step) 
$b=$value, returing 1.  
swapping: $A[1] and $A[2] 
$A looks like this now: [1,3,2,4,2,1,2], comparing [1,3] (insertion step) 
$a=$value, returing 0.  
$A looks like this now: [1,3,2,4,2,1,2], insertion done 
Sorted Subarray from $A is [1,3,2] 
$A looks like this now: [1,3,2,4,2,1,2], comparing [2,4] (verify step) 
$b=$value, returing 1.  
swapping: $A[2] and $A[3] 
$A looks like this now: [1,3,4,2,2,1,2], comparing [3,4] (insertion step) 
$a=$value, returing 0.  
$A looks like this now: [1,3,4,2,2,1,2], insertion done 
Sorted Subarray from $A is [1,3,4,2] 
$A looks like this now: [1,3,4,2,2,1,2], comparing [2,2] (verify step) 
$a=$value, returing 0.  
Sorted Subarray from $A is [1,3,4,2,2] 
$A looks like this now: [1,3,4,2,2,1,2], comparing [2,1] (verify step) 
$b=$value, returing 1.  
swapping: $A[4] and $A[5] 
$A looks like this now: [1,3,4,2,1,2,2], comparing [2,1] (insertion step) 
$b=$value, returing 1.  
swapping: $A[3] and $A[4] 
$A looks like this now: [1,3,4,1,2,2,2], comparing [4,1] (insertion step) 
$b=$value, returing 1.  
swapping: $A[2] and $A[3] 
$A looks like this now: [1,3,1,4,2,2,2], comparing [3,1] (insertion step) 
$b=$value, returing 1.  
swapping: $A[1] and $A[2] 
$A looks like this now: [1,1,3,4,2,2,2], comparing [1,1] (insertion step) 
$a=$value, returing 0.  
$A looks like this now: [1,1,3,4,2,2,2], insertion done 
Sorted Subarray from $A is [1,1,3,4,2,2] 
$A looks like this now: [1,1,3,4,2,2,2], comparing [2,2] (verify step) 
$a=$value, returing 0.  
Sorted Array $A is [1,1,3,4,2,2,2] 

【讨论】:

  • 非常感谢您提供的信息。从现在起的一周或更长时间内,我不会达到这一点。说在排序过程完成之前数组不会改变是否正确?您破坏了排序,但是当我在运行代码的某些点对数组进行 var_dump 时,它总是一样的。
  • @now_m 在usort/uasort 的 PHP 数组代码(例如版本 7.0.24)中,可能还有其他用户回调,有一个 comment about making a copy 隐藏修改从用户回调中,这就是您看不到修改的原因。它没有记录在案,所以你不应该假设任何事情,因为它可能会随着不同的 PHP 版本而改变。
  • 我仍然不明白它是如何工作的。有 $order 数组,它与 $a-$b 对进行比较。这里唯一的机制是当 list_cmp 函数返回 1 时,当前的 $b 值被移向数组的开头(较低的索引;总是 $b 并且总是这个方向)。如果 list_cmp 回调返回 1,什么是“运行”为 $b 找到正确位置的机制?这是内置在 usort() 中的,这就是它的工作原理?可能不会,因为我们不是在创建像 1,2,3,4,5,6,7,8,9 这样的东西,而是像这样的东西 1,1,3,4,2,2,2
  • @now_m 我不确定您是否对算法或排序顺序背后的整个理论有疑问。 algorithmic part 是直截了当的。它所做的只是从“左”(最低索引)到“右”(最高索引)检查每个邻居对是否按顺序排列(并且list_cmp 定义了这个顺序)。如果遇到不合适的对(list_cmp 返回1),则将右侧元素向左移动并再次使用新的左侧进行检查。这一直持续到它适合(list_cmp 返回0)或到达列表开始。没有魔法。
  • @now_m 我选择了简单的道路并学习了 IT。 ;) 除了其他课程的数学和编程基础知识外,我们还有一门课程(半年,每周大约 8 小时和家庭作业)关于基本数据结构和算法,如排序、“分治”原则、列表/树数据结构,在运行时/内存方面证明正确性和复杂性。我只能想象在纯粹的自学中这是多么困难。不要离题太远:该课程通常称为“算法简介”,您可能想查看一下。除了一些(昂贵的)书籍之外,还有很多免费的网络资源。
猜你喜欢
  • 2021-08-18
  • 1970-01-01
  • 2020-03-23
  • 2014-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多