排序数组值而不使用像 sort() 等内置的 php

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12409040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:30:13  来源:igfitidea点击:

sorting array value without using built in php like sort() etc

php

提问by Bashar Gh

<?php
function sortArray() {
    $inputArray = array(8, 2, 7, 4, 5);
    $outArray = array();
    for($x=1; $x<=100; $x++) {
        if (in_array($x, $inputArray)) {
            array_push($outArray, $x);
        }
    }
    return $outArray;
}


$sortArray = sortArray();
foreach ($sortArray as $value) {
    echo $value . "<br />";
}
?>

I have this code but there are two problems

我有这个代码,但有两个问题

  • What if my numbers in array are greater than 100?
  • Also, I'd like to see more than one method of sorting
  • 如果数组中的数字大于 100 怎么办?
  • 另外,我想看到不止一种排序方法

回答by Tania

Here is the way of sorting.

下面是排序的方法。

<?php

$array=array('2','4','8','5','1','7','6','9','10','3');

echo "Unsorted array is: ";
echo "<br />";
print_r($array);


for($j = 0; $j < count($array); $j ++) {
    for($i = 0; $i < count($array)-1; $i ++){

        if($array[$i] > $array[$i+1]) {
            $temp = $array[$i+1];
            $array[$i+1]=$array[$i];
            $array[$i]=$temp;
        }       
    }
}

echo "Sorted Array is: ";
echo "<br />";
print_r($array);

?>

回答by rahul sharma

    $arr= array(110,20,130,100,2);

    for($i=0; $i<count($arr)-1; $i++)
    {
        for($j=0; $j<count($arr)-1; $j++)
        {
            if($arr[$j]> $arr[$j+1]){
                $temp= $arr[$j+1];
                $arr[$j+1]= $arr[$j];
                $arr[$j]= $temp;
            }
        }

    }
    print_r($arr);

回答by Brajinder Singh

All the accepted answers here are good, and most of them use two for loops to sort an array. At first the code seemed fairly straight and even I thought of the same. But then I wanted to investigate further. How efficient is this method? So I created an array of a 10,000 "count" or values and wrote it in a file to be included later on, for consistency, using the following for code:

这里接受的所有答案都很好,其中大多数使用两个 for 循环对数组进行排序。起初,代码看起来很简单,甚至我也这么想。但后来我想进一步调查。这种方法的效率如何?因此,我创建了一个包含 10,000 个“计数”或值的数组,并将其写入一个文件中,以便稍后包含,为了保持一致性,使用以下代码:

$str = "<?php \n $array = array( \n";
for($x = 0; $x <= 10000; $x++){
    $str .= mt_rand(0,10000).",\n";
}
$str .= "); \n ?>";

$file = fopen('req_arr.php', 'w+');
echo fwrite($file,$str);
fclose($file);

include_once('req_arr.php');

$arr = $array;

Then I used the two for loops method as given by most of the guys here, and also measured the time taken:

然后我使用了这里大多数人给出的两种 for 循环方法,并测量了所花费的时间:

    $start = microtime(1);
    $cnt = count($arr);
    for($i = 0; $i < $cnt; $i++ ){
        for($j = 0; $j < $cnt-1; $j++ ){
            $temp = '';
            if($arra[$j] > $arra[$j+1]){
                $temp = $arr[$j];
                $arr[$j] = $arr[$j+1];
                $arr[$j+1] = $temp;
            }
        }
    }
    $stop = microtime(1);
    echo $stop - $start;
    echo '<pre>'; print_r($arr);

And this gave the execution time (in seconds) to be 7.5408220291138.

这使执行时间(以秒为单位)为7.5408220291138

Note: This code was tested in XAMPP on Windows10, 64 bit, i7 gen 4, 8 GB RAM, and in Chrome.

注意:此代码在 Windows10、64 位、i7 gen 4、8 GB RAM 和 Chrome 上的 XAMPP 中进行了测试。

This is way too much. I'm sure PHP can't be this sloppy. So next I tested the in-built PHP rsort() function, using the following code:

这太过分了。我敢肯定 PHP 不能这么草率。所以接下来我使用以下代码测试了内置的 PHP rsort() 函数:

$start = microtime(1);
rsort($arr, SORT_NUMERIC);
$stop = microtime(1);
echo $stop - $start;
echo '<pre>'; print_r($arr);    

This time, the execution time was just 0.0033688545227051seconds. JUST 0.0033688545227051 SECONDS for sorting a 10,000 values array. Clearly, the two for loop method is inefficient to whatever PHP is using in its core.

这一次,执行时间仅为0.0033688545227051秒。只需 0.0033688545227051 秒即可对 10,000 个值数组进行排序。显然,无论 PHP 在其核心中使用什么,这两个 for 循环方法都是低效的。

A quick research on Google/PHP.net gave me the answer that PHP uses quicksort algorithm to sort indexed array, and that it doesn't uses two for loops but recursive function. I dug deeper and found a few examples of quicksearch for C++, Java etc. So, I replicated them in PHP, as follows:

对 Google/PHP.net 的快速研究给了我答案,即 PHP 使用快速排序算法对索引数组进行排序,并且它不使用两个 for 循环而是使用递归函数。我挖得更深一些,找到了几个C++、Java等快速搜索的例子,所以,我在PHP中复制了它们,如下:

/*
    The main function that implements QuickSort
    arr --> Array to be sorted,
    low  --> Starting index,
    high  --> Ending index
*/
function quickSort(&$arr, $low, $high)
{
    if ($low < $high)
    {
        /* pi is partitioning index, arr[p] is now
           at right place */
        $pi = partition($arr, $low, $high);
        // Separately sort elements before
        // partition and after partition
        quickSort($arr, $low, $pi - 1);
        quickSort($arr, $pi + 1, $high);
    }

    return $arr;
}

function partition (&$arr, $low = 0, $high)
{
    $pivot = $arr[$high];  // pivot
    $i = ($low - 1);  // Index of smaller element

    for ($j = $low; $j <= $high-1; $j++)
    {
        // If current element is smaller than or
        // equal to pivot
        if ($arr[$j] <= $pivot)
        {
            $i++;    // increment index of smaller element
            swap($arr[$i], $arr[$j]);
        }
    }
    swap($arr[$i + 1], $arr[$high]);
    return ($i + 1);
}

function swap(&$a, &$b){
    $t = $a;
    $a = $b;
    $b = $t;
}

Obviously, this could be further optimized but I just wanted to get something running and see the results, and this was sufficient. So, now let's see the results:

显然,这可以进一步优化,但我只是想让一些东西运行并查看结果,这就足够了。那么,现在让我们看看结果:

$start = microtime(1);
$sarr = quickSort($array, 0, $cnt-1);
$stop = microtime(1);
echo $stop - $start;
echo '<pre>';print_r($sarr);
die();

The time taken by this algorithm came out be: 0.022707939147949

这个算法花费的时间出来是:0.022707939147949

Still, not as fast as rsort() but satisfactory. I tried the same with a million values array too but the two for loops array just exhausted the memory and I decided even 10,000 value array proves the theory well.

尽管如此,不如 rsort() 快,但令人满意。我也对一百万个值数组进行了同样的尝试,但是两个 for 循环数组刚刚耗尽了内存,我决定即使是 10,000 个值数组也很好地证明了这个理论。

Cheerrrssss...

啦啦啦...

回答by sumon cse-sust

//Best solution for bubble sort
$a = [10,5,2,8,7];
$k = 0;//I used this variable because i want to show you how many times my for loop needs to iterate maximum.
for($i = 0;$i < count($a); $i++){
    for($j = 1; $j < count($a) - $i; $j++){
        if($a[$j -1 ] > $a[$j]){
            $temp = $a[$j];
            $a[$j] = $a[$j -1];
            $a[$j - 1] = $temp;
        }
        $k++;
    }

}
echo $k;
echo '<pre>';
print_r($a);
echo '</pre>';

回答by Carlos Espinoza

This is my Quicksort algorithmin PHP:

这是我在 PHP 中的快速排序算法

<?php
$array = [1, 4, 3, 5, 9, 6, 1, 6, 4, 1, 1, 4, 5, 6, 6, 7, 2, 1, 4, 0];
$j = count($array);
$t = $j-1;
while($j>=0){
    for ($i=0; $i < $t; $i++) { 
        $aux = $array[$i]; 
        if($array[$i]>$array[$i+1]){
            $array[$i] = $array[$i+1];
            $array[$i+1] = $aux;
        }
    }
    $j--;
}
print_r($array);

回答by WebGhost

$q = [1,3,6,2,8,9,4];  //let's say any array

for($i = 0; $i<=count($q)-1;$i++){
  for($j =0; $j<count($q)-1;$j++){
     if($q[$j] < $q[$j+1]){         //for ASC or DESC just switch '>' or '<'
          $var = $q[$j+1];
          $q[$j+1] = $q[$j];
          $q[$j]=$var;              
     }
   }
}
print_r($q);  //This is sorted array'

回答by Surendra Sonkar

//Here is the simplest way of sorting...
$list = array('5','15','7','12','39','1','5');
$a;
$b;
for($i=0;$i<count($list);$i++){ 
    for($j=0;$j<count($list);$j++){
        if($list[$i] < $list[$j]){
            $a = $list[$j]; 
            $b = $list[$i];     

            $list[$i] = $a;
            $list[$j] = $b;
        }
    }
}

回答by Pranav Chavan

$arr = array(8, 2, 7, 4, 5);

for($j=0; $j <= count($arr)-1; $j++){
  for($i=0; $i <= count($arr)-1; $i++){

      if( $arr[$i] < $arr[$j]){  //'<' or '>' operator for Asc, Dec.
         $temp = $arr[$i];
         $arr[$i] = $arr[$j];
         $arr[$j] = $temp;
      }
}
echo'<pre>';
print_r($arr);

回答by Mazen El-Gammal

Here is the right solution in php:

这是php中的正确解决方案:

$array=array('2','4','8','5','1','7');

for($i=1;$i< count($array);$i++)
{
   for($j=$i;$j>0;$j--)
   {    
       if($array[$j] < $array[$j-1])
       { 
           $tmp = $array[$j];
           $array[$j] = $array[$j-1];
           $array[$j-1] = $tmp ;
       }
   }
}

回答by Mohammed Raish Sayyed

We can use a Bubble Sortfor sorting.

我们可以使用冒泡排序进行排序。

The best-case performance of O(n). Otherwise, best-case == worse-case == average-case == O(n^2)

O(n) 的最佳性能。否则,最好的情况 == 最坏的情况 == 平均情况 == O(n^2)

$Obj1 = array(20, 30, 10, 50, 40, 60, 100, 90, 80, 70);

 $temp;

print_r($Obj1);


for ($i = 0; $i < sizeof($Obj1) - 1; $i++) {

for ($j = sizeof($Obj1) - 1; $j > $i; $j--) {
    if ($Obj1[$j - 1] > $Obj1[$j]) {
        $temp = $Obj1[$j-1];
        $Obj1[$j-1] = $Obj1[$j];
        $Obj1[$j] = $temp;
        $temp = 0;
    }
}

}

print_r($Obj1);