美文网首页
直接插入排序,PHP实现

直接插入排序,PHP实现

作者: designer | 来源:发表于2020-06-17 22:31 被阅读0次

思路:

  • 1、选择第一个元素作为有序数组a
  • 2、取出下一个元素x,从后往前依次遍历有序数组a
  • 3、如果有序数组元素大于x,则将有序数组元素后移一个位置
  • 4、如果有序元素数组小于x,则x插入到当前元素的后面
  • 5.重复上述2,3,4步骤
<?php
/**
 * Created by PhpStorm.
 * User: fql
 * Date: 2020/6/17
 * Time: 下午10:42
 */
namespace app\index\controller;
/**
 * Class InsertSort
 * 1、选择第一个元素作为有序数组a
 * 2、取出下一个元素x,从后往前依次遍历有序数组a
 * 3、如果有序数组元素大于x,则将有序数组元素后移一个位置
 * 4、如果有序元素数组小于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++ ){
            //将下一个元素排序到已经排序的数组里面
            $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实现

      本文链接:https://www.haomeiwen.com/subject/vmbexktx.html