php - 如何检查数字 2D PHP 数组的值是否按 'incereasing' 、 'descending' 或 'mixed' 顺序排列?

标签 php arrays sorting

我正在寻找一种方法来检查数字 2D PHP 数组的值是否在

增加降序 , 或者 混合订单。

示例:

array( 1, 2, 3, 4 ) // This is an incereasing numeric array
array( 4, 3, 2, 1 ) // This is a descending numeric array
array( 1, 3, 2, 4 ) // This is a mixed numeric array

我怎样才能检查它? (我正在寻找一种快速的方法,它需要快速运行)

最佳答案

我认为,如果您正在寻找快速解决方案(即快速工作),您必须使用以下数据数组:

function getOrder($rgData)
{
   if(!count($rgData) || count($rgData)==1)
   {
      return null;
   }
   $sCurrent = (string)array_shift($rgData);
   $iOrder   = current($rgData)>$sCurrent?1:-1;
   foreach($rgData as $mValue)
   {
      if(($sCurrent>(string)$mValue && $iOrder== 1) ||
         ($sCurrent<(string)$mValue && $iOrder==-1))
      {
         return 0;
      }
      $sCurrent = (string)$mValue;
   }
   return $iOrder;
}

这将为相应的升序、混合和降序返回 1,0 和 -1。请注意,所有值都将被视为字符串并进行比较。此方法更有用,因为它具有 O(N) 复杂度(在最坏情况下),而使用 sort() 函数将导致 O(N log(N )) 复杂性(最好情况下)

关于php - 如何检查数字 2D PHP 数组的值是否按 'incereasing' 、 'descending' 或 'mixed' 顺序排列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18715028/

相关文章:

php - 从 SQL 打印到 PHP?

php - 让页面在访问者刷新时更新字段

java - 如何修改数组中的后续点

c - 排序函数,helpers.c,只列出了几个数字

php - 在 Prestashop 中自定义注册表单

php - 为什么相同的 http 请求在浏览器中有效,但从我的 Android 应用程序发送时却失败了?

php - 如何在 PHP 中使用 array_walk 对三维数组进行排序?

python - 如何将物体随机放置在不同角度和不同位置的python上

ios - 排序 Mapbox 注释

c++ - 带有 std::map<T*, U> 的程序是否具有明确定义的行为?