【问题标题】:Sorting arrays manually in php without using sort() [closed]在不使用 sort() 的情况下在 php 中手动对数组进行排序 [关闭]
【发布时间】:2014-10-23 07:46:01
【问题描述】:

帮助。在不使用 sort() 的情况下,我已经在打印排序数组列表时陷入了逻辑和过程。

<?php
$item = array(2, 1, 3);
$item_length = count($item);
for ($counter = 0; $counter < $item_length; $counter++) {
  if ($item[$counter] <= $item[$counter + 1]) {
   print $item[$counter];

   // now what I should do??

   }

 }
?> 

【问题讨论】:

  • 比较明智的做法是先排序,再打印,否则要循环很多很多...
  • 是的,我已经使用 sort() 做到了,但是学校指示我们不要使用 sort()。我陷入了无效的结果... :-(
  • 你需要一个嵌套循环来排序这个数组。

标签: php sorting


【解决方案1】:

这是使用冒泡排序的解决方案

<?php
$item = array(2, 1, 4,3,5,6);
$item_length = count($item);
for ($counter = 0; $counter < $item_length-1; $counter++) {
  for ($counter1 = 0; $counter1 < $item_length-1; $counter1++) {
    if ($item[$counter1] > $item[$counter1 + 1]) {
       $temp=$item[$counter1];
       $item[$counter1]=$item[$counter1+1];
       $item[$counter1+1]=$temp;
       }
    }
 }

//you can print the array using loop
print_r($item);
?> 

【讨论】:

  • 非常感谢,非常感谢......我只是迷失了逻辑......我已经阅读了关于冒泡排序的内容,但我无法通过它的技术术语来理解它......我只会将其用作逻辑基础...
【解决方案2】:
<?php
    $item = array(2, 1, 3);
    $item_length = count($item);
    for ($counter = 0; $counter < $item_length; $counter++) {
        for ($t = $counter+1; $t < $item_length; $t++) {
            if ($item[$counter] < $item[$t]) {
                swapItem($counter,$t); // your function to swap two item with index
            }                                                                            
        }
    }
?>

基本的排序功能会是这样的

【讨论】:

  • 谢谢 Tory.. 我已经在 15 分钟前想通了 :-) 但你的方法不同。我没有想到 swapItem()
  • 我的意思是:SwapItem ($index1, $index2) { $temp=$item[$index1]; $item[$index1]=$item[$index2]; $item[$index2]=$temp; } ||如果你失去了逻辑,我可以帮助你。如果需要,请随时与我联系。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 2016-04-24
  • 2011-07-19
相关资源
最近更新 更多