Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php中的Corman插入排序不起作用_Php_Arrays_Algorithm_Sorting_Insertion Sort - Fatal编程技术网

php中的Corman插入排序不起作用

php中的Corman插入排序不起作用,php,arrays,algorithm,sorting,insertion-sort,Php,Arrays,Algorithm,Sorting,Insertion Sort,算法 for k from 2 to n key = a[k] j = k - 1 while (j > 0 and key > a[j]) a[j + 1] = a[j] j = j - 1 end while a[j + 1] = key end for 我的代码: 函数插入排序(数组$array){ $length=计数($array); 对于($i=1;$i0&&$array[$j]>$element){ $array[$j+1]=$

算法

for k from 2 to n
  key = a[k]
  j = k - 1

  while (j > 0 and key > a[j])
    a[j + 1] = a[j]
    j = j - 1
  end while

  a[j + 1] = key
end for
我的代码:

函数插入排序(数组$array){
$length=计数($array);
对于($i=1;$i0&&$array[$j]>$element){
$array[$j+1]=$array[$j];
$j=$j-1;
}
$array[$j+1]=$element;
}
返回$array;
}
输出:

Array (
    [0] => 5
    [1] => 6
    [2] => 4
    [3] => 3
    [4] => 2
    [5] => 1
)

我在这里做错了什么,为什么第一个元素没有排序?

嘿,请检查算法和PHP代码中wile循环的第二个条件,它可能会帮助您……

while($j>0&&$array[$j]>$element){
…也许
while($j>=0&&$array[$j]>$element){
太棒了,谢谢你。我太蠢了,竟然没注意到。