PHP Array -- PHP排序 -- 插入排序(Insertion Sort)
2009-03-16 20:31
585 查看
对于小规模的数组(特别是已经相当有序的小数组),插入排序是比较有效的算法 -- 这种算法把数据分成两部分:已经排序部分和还未排序部分,然后进入未排序部分,逐次从中去除一个值,然后再以排序部分里循环,把整个值插入到正确位置,并且把其他值向后移动一个位置。不断重复这个过程,直到全部值都移动到已排序部分。
插入排序是其他更好排序算法的基础。
// 来自 PHP5 in Practice (U.S.)Elliott III & Jonathan D.Eisenhamer
插入排序是其他更好排序算法的基础。
// 来自 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} "; } ?>
相关文章推荐
- 插入排序 直接插入排序的PHP实现 Straight Insertion Sort
- 算法从排序开始——插入排序(Insertion Sort)C语言及Java实现
- 【DS】排序算法之插入排序(Insertion Sort)
- 算法:冒泡排序(Bubble Sort)、插入排序(Insertion Sort)和选择排序(Selection Sort)总结
- 排序——插入排序(insertionsort)
- PHP Array -- PHP 排序 -- 反复排序 (Toggle Sort)
- Insertion Sort List 使用插入排序将链表排序
- PHP Array -- PHP 排序 -- 希尔排序(Shell Sort)
- 算法学习记录-排序——插入排序(Insertion Sort)
- 插入排序:直接插入排序-Direct insertion sort
- Python 数据结构与算法——插入排序(insertion sort)
- 1.插入排序—直接插入排序(Straight Insertion Sort)
- InsertionSort_插入排序
- PHP中的排序函数sort、asort、rsort、krsort、ksort区别分析
- 单链表元素排序(Insertion sort list)
- 插入排序Insertion Sort
- PHP实现快速排序、插入排序、选择排序
- 插入排序(Insertion sort)
- 排序算法——插入排序(Insertion Sort)
- Insertion Sort List 链表插入排序