zoukankan      html  css  js  c++  java
  • PHP 插入排序 -- 直接插入排序

    1)直接插入序 -- Straight Insertion Sort

    时间复杂度 :O(n^2)    

    适用条件: 适合记录数不多的情况

     1 <?php
     2 $a = [0 =>3,4,5,1,11,9,27,18,20];  // "[]" 语法 --  >= PHP5.4 版本
     3 
     4 /**
     5  * 直接插入排序
     6  * 在已经排好序的队列插入新的记录
     7  * @param array $list
     8  */
     9 function straightInsertSort(array &$list)
    10 {
    11     $guard = 0;
    12 
    13     $list = array_values($list);   // 不去除相同的Value值
    14     $len = count($list);
    15     array_unshift($list,$guard);  // 放置监视哨
    16     for($i = $list[2];$i <= $len; ++$i)
    17     {
    18         if($list[$i] < $list[$i-1])
    19         {
    20             $list[0] = $list[$i];
    21             $list[$i] = $list[$i-1];
    22             $j = $i - 2;
    23             while($list[0] < $list[$j])
    24             {
    25                 if($list[$j] > $list[0])
    26                 {
    27                     $list[$j+1] = $list[$j];
    28                 }
    29                 --$j;
    30             }
    31             $list[$j+1] = $list[0];
    32         }
    33     }
    34     array_shift($list);
    35 }
    36 straightInsertSort($a);
    37 print_r($a);

    输出结果:

    学习记录,方便复习
  • 相关阅读:
    mac 下 安装 mongodb
    ajax常见的面试问题
    js 数组api
    vue 项目中的坑 在项目中遇到 持续更新ing
    移动端适配问题
    axios API速查表
    移动端常用的 meta设置
    python 首次安装 报错
    在vue项目中使用sass
    SPA单页面应用
  • 原文地址:https://www.cnblogs.com/jingjingdidunhe/p/6476484.html
Copyright © 2011-2022 走看看