您的位置:首页 > 编程语言 > PHP开发

PHP Array -- PHP排序 -- 插入排序(Insertion Sort)

2009-03-16 20:31 507 查看
对于小规模的数组(特别是已经相当有序的小数组),插入排序是比较有效的算法 -- 这种算法把数据分成两部分:已经排序部分和还未排序部分,然后进入未排序部分,逐次从中去除一个值,然后再以排序部分里循环,把整个值插入到正确位置,并且把其他值向后移动一个位置。不断重复这个过程,直到全部值都移动到已排序部分。

插入排序是其他更好排序算法的基础。

// 来自 PHP5 in Practice (U.S.)Elliott III & Jonathan D.Eisenhamer

<?php
// Implement the Insertion Sort
function insertion_sort(&$a) {
// Loop through all entries in the array
$count = count($a);
for ($i = 0; $i < $count; $i++) {
// Save the current value which we are going to compare:
$value = $a[$i];

// Now loop backwards from the current value until we reach the
//  beginning of the array or a value less than our current one
for ($x = $i - 1; ( ($x >= 0) && ($a[$x] > $value) ); $x--) {
// Swap this value down one place:
$a[$x + 1] = $a[$x];
}

// Now assign our value to it's proper sorted position:
$a[$x + 1] = $value;
}
}

// Prepare an array of values:
$values = array(73, 3, 42, 6, 14, 23, 15, 9, 74, 1, 234, 45, 23, 76, 12, 3);
// Sort them:
insertion_sort($values);
// Echo them out in order:
//  1 3 3 6 9 12 14 15 23 23 42 45 73 74 76 234
foreach ($values as $v) { echo "{$v} "; }
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: