php插入式排序的两种写法。

WBOY
Release: 2016-06-23 13:25:56
Original
1114 people have browsed it

百度了下插入式排序,百度百科中php版本的插入式排序如下:

 1 function insert_sort($arr) { 2     // 将$arr升序排列 3     $count = count($arr); 4     for ($i=1; $i<$count; $i++) { 5         $tmp = $arr[$i]; 6         $j = $i - 1; 7         while ($j >=0 && $arr[$j] > $tmp) { 8             $arr[$j+1] = $arr[$j]; 9             $j--;10         }11         if (($j+1) != $i) {12             $arr[$j+1] = $tmp;            13         }14     }15     return $arr;16 }
Copy after login

看着实在是别扭,然后就翻了下Robert Sedgewick写的《算法》,书中的代码都是用java实现的,在这里将插入式排序改用php重写一下:

 1 function new_insert_sort($arr) { 2     // 将$arr升序排列 3     $count = count($arr); 4     for ($i=1; $i<$count; $i++) {// 索引,完成一次插入就需要将索引$i右移 5         // 将arr[i]插入到a[i-1]、a[i-2]、a[i-3]...之中,也就是如果符合条件就交换位置 6         for ($j=$i; $j>0 && $arr[$j] < $arr[$j-1]; $j--) { 7             $tmp = $arr[$j]; 8             $arr[$j] = $arr[$j-1]; 9             $arr[$j-1] = $tmp;10         }11     }12     return $arr;13 }
Copy after login

我觉得第二种写法更容易让人理解,就像《算法》中写到:插入式排序就像爱玩扑克牌的人整理牌一样,将每一张牌插入到其他已经排好序的牌的适当位置。另外,百度时还发现了博客园的文章Frank Fan的文章插入式排序,也可以看看。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!