PHP排序算法:插入排序 (一维数组)
2016-07-19 00:00
543 查看
摘要: PHP插入排序算法实现
最坏时间复杂度:O(n2)
稳定性:稳定
![](https://static.oschina.net/uploads/space/2018/0410/012517_nOe7_1159632.png)
遍历数组,每次把一个待排序的元素,插入到前面已经排好序的数列中的恰当位置,使数列依然有序。知道待排序的元素全部插入完为止。就得到了一个排序号的数组。
$toSort == 1时: [23, 34 , 4 , 7 , 13 , 43 , 6 , 12 , 56 , 2]
$toSort == 2时: [4 , 23 , 34 , 7 , 13 , 43 , 6 , 12 , 56 , 2]
$toSort == 3时: [4 , 7 , 23 , 34 , 13 , 43 , 6 , 12 , 56 , 2]
$toSort == 4时: [4 , 7 , 13 , 23 , 34 , 43 , 6 , 12 , 56 , 2]
$toSort == 5时: [4 , 7 , 13 , 23 , 34 , 43 , 6 , 12 , 56 , 2]
$toSort == 6时: [4 , 6 , 7 , 13 , 23 , 34 , 43 , 12 , 56 , 2]
$toSort == 7时: [4 , 6 , 7 , 12 , 13 , 23 , 34 , 43 , 56 , 2]
$toSort == 8时: [4 , 6 , 7 , 12 , 13 , 23 , 34 , 43 , 56 , 2]
$toSort == 9时: [2 , 4 , 6 , 7 , 12 , 13 , 23 , 34 , 43 , 56]
输出
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 7 [4] => 12 [5] => 13 [6] => 23 [7] => 34 [8] => 43 [9] => 56 )
时间复杂度:
最优时间复杂度:O(n) (升序排列,序列已经处于升序状态)最坏时间复杂度:O(n2)
稳定性:稳定
原理与实现:
![](https://static.oschina.net/uploads/space/2018/0410/012517_nOe7_1159632.png)
遍历数组,每次把一个待排序的元素,插入到前面已经排好序的数列中的恰当位置,使数列依然有序。知道待排序的元素全部插入完为止。就得到了一个排序号的数组。
$array = [34,23,4,7,13,43,6,12,56,2];
$toSort == 1时: [23, 34 , 4 , 7 , 13 , 43 , 6 , 12 , 56 , 2]
$toSort == 2时: [4 , 23 , 34 , 7 , 13 , 43 , 6 , 12 , 56 , 2]
$toSort == 3时: [4 , 7 , 23 , 34 , 13 , 43 , 6 , 12 , 56 , 2]
$toSort == 4时: [4 , 7 , 13 , 23 , 34 , 43 , 6 , 12 , 56 , 2]
$toSort == 5时: [4 , 7 , 13 , 23 , 34 , 43 , 6 , 12 , 56 , 2]
$toSort == 6时: [4 , 6 , 7 , 13 , 23 , 34 , 43 , 12 , 56 , 2]
$toSort == 7时: [4 , 6 , 7 , 12 , 13 , 23 , 34 , 43 , 56 , 2]
$toSort == 8时: [4 , 6 , 7 , 12 , 13 , 23 , 34 , 43 , 56 , 2]
$toSort == 9时: [2 , 4 , 6 , 7 , 12 , 13 , 23 , 34 , 43 , 56]
$count = count($array); for($toSort = 1;$toSort < $count;$toSort++){ //当前要插入的值 $insert = $array[$toSort]; for($sorted = $toSort - 1;$sorted >= 0;$sorted--){ //待插入元素比已排好序的要小,换位 if($insert < $array[$sorted]){ $array[$sorted + 1] = $array[$sorted]; $array[$sorted] = $insert; //待插入前面的已经是排好序的,就不用比较换位了 }else{ break; } } } print_r($array);
输出
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 7 [4] => 12 [5] => 13 [6] => 23 [7] => 34 [8] => 43 [9] => 56 )
相关文章推荐
- Why was SCTP Selected for WebRTC’s Data Channel?
- CCNP笔记——MST上
- WebRTC Data Channels RFC
- PHP JSON数组与对象的理解
- PHP书写规范 PHP Coding Standard
- PHP
- php-删除非空目录
- PHPExcel 的使用
- php-递归创建级联目录
- 分布式部署lamp,phpmyadmin,wordpress的安装与应用
- php cli模式下获取参数的方法
- [php学习六]AJAX练习3-实时搜索
- 理清ThinkPHP的目录结构及访问规则,创建第一个控制器
- 安装icephp 记
- 【php】面向对象
- php-composer-phar常用命令集
- php最基本的增删改查
- pureftpd的搭建
- win8.1 删除 我的电脑中 蓝牙FTP 图标
- PHP超级全局数组$_FILES