插入排序 php,直接插入排序,PHP实现
思路:
1、選擇第一個元素作為有序數(shù)組a
2、取出下一個元素x,從后往前依次遍歷有序數(shù)組a
3、如果有序數(shù)組元素大于x,則將有序數(shù)組元素后移一個位置
4、如果有序元素數(shù)組小于x,則x插入到當前元素的后面
5.重復上述2,3,4步驟
/**
* Created by PhpStorm.
* User: fql
* Date: 2020/6/17
* Time: 下午10:42
*/
namespace app\index\controller;
/**
* Class InsertSort
* 1、選擇第一個元素作為有序數(shù)組a
* 2、取出下一個元素x,從后往前依次遍歷有序數(shù)組a
* 3、如果有序數(shù)組元素大于x,則將有序數(shù)組元素后移一個位置
* 4、如果有序元素數(shù)組小于x,則x插入到當前元素的后面
* 5.重復上述2,3,4步驟
*/
class InsertSort extends \think\Controller
{
public function sort(){
$arr = [100,78,34,56,21,33,90,31,67,54];
$this->InsertSort($arr);
dump($arr);
}
public function InsertSort(&$array){
$len = count($array);
for($currentIndex = 1;$currentIndex < $len;$currentIndex++ ){
//將下一個元素排序到已經排序的數(shù)組里面
$this->sortCurrent($array,$currentIndex);
}
}
private function sortCurrent(&$array,$currentIndex){
$currentValue = $array[$currentIndex];
for($sortedIndex = $currentIndex - 1;$sortedIndex >= 0;$sortedIndex--) {
if($array[$sortedIndex] > $currentValue ){
$array[$sortedIndex + 1] = $array[$sortedIndex];
if($sortedIndex==0){
$array[$sortedIndex] = $currentValue;
}
}else{
$array[$sortedIndex + 1] = $currentValue;
break;
}
}
}
}
總結
以上是生活随笔為你收集整理的插入排序 php,直接插入排序,PHP实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《跟我学java》_《跟我学Java——
- 下一篇: php常用操作数组函数,PHP自带的几个