forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request wangzheng0822#294 from git-zjx/patch-5
PHP Notice: Undefined offset
- Loading branch information
Showing
1 changed file
with
14 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,24 +1,25 @@ | ||
<?php | ||
|
||
function insertSort(&$arr) | ||
function insertionSort(&$arr) | ||
{ | ||
$i = 0; | ||
$len = count($arr); | ||
$n = count($arr); | ||
if ($n <= 1) return; | ||
|
||
while($i < $len){ | ||
$data = $arr[$i+1]; | ||
for ($j = $i;$j >=0 ;$j-- ){ | ||
if ($data >= $arr[$j]){ | ||
array_splice($arr, $i+1, 1); | ||
array_splice($arr, ++$j, 0, $data); | ||
for ($i = 1; $i < $n; ++$i) { | ||
$value = $arr[$i]; | ||
$j = $i - 1; | ||
// 查找插入的位置 | ||
for (; $j >= 0; --$j) { | ||
if ($arr[$j] > $value) { | ||
$arr[$j + 1] = $arr[$j]; // 数据移动 | ||
} else { | ||
break; | ||
} | ||
} | ||
|
||
$i++; | ||
$arr[$j + 1] = $value; // 插入数据 | ||
} | ||
} | ||
|
||
$arr = [1,4,6,2,3,5,4]; | ||
insertSort($arr); | ||
var_dump($arr); | ||
insertionSort($arr); | ||
var_dump($arr); |