<?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 />";
}
?>
我有这段代码,但有两个问题
- 如果我在数组中的数字大于 100 怎么办?
- 另外,我希望看到多种排序方法
这是排序方法。
<?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);
?>
大多数其他答案使用两个 for 循环对数组进行排序。起初,代码似乎相当直接,甚至我也想到了同样的想法。但后来我想进一步调查。这种方法的效率如何?因此,使用包含 10,000 个值的数组,我使用了两个 for loops 方法,并获得了 7.5 秒的执行时间
这太过分了。我相信PHP不能这么草率。所以接下来我测试了内置的 PHP rsort()
函数,得到了 0.003 秒的时间。
一些研究给了我答案,PHP 使用快速排序算法对带有递归函数的索引数组进行排序。我深入研究并发现了一些快速搜索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;
}
该算法花费的时间是:0.023秒。没有rsort()
那么快,但令人满意。
这是我
在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);
不使用内置方法对数组进行排序,但所有答案都使用预定义的方法count
.
我只是想重构它。请找到以下答案。
$array = [50,12, 30, 10, 9, 14];
$count = 0;
foreach($array as $elem){
$count++;
}
for ($i = 0; $i < $count; $i++) {
for ($j = 0; $j < $count - 1; $j++) {
if ($array[$j] > $array[$j + 1]) {
$temp = $array[$j];
$array[$j] = $array[$j + 1];
$array[$j +1] = $temp;
}
}
}
print_r($array);