你好,欢迎来到电脑编程技巧与维护杂志社! 杂志社简介广告服务读者反馈编程社区  
合订本订阅
 
 
您的位置:技术专栏 / Web开发
PHP实现插入排序算法
 

插入排序(Insertion Sort),是一种较稳定、简单直观的排序算法。插入排序的工作原理,是通过构建有序序列,对于未排序的数据,在有序序列中从后向前扫描,找到合适的位置并将其插入。插入排序,在最好情况下,时间复杂度为O(n);在最坏情况下,时间复杂度为O(n2);平均时间复杂度为O(n2)。

插入排序示例图:

\
  <?php
/**
 * 数据结构与算法(PHP实现) - 插入排序(Insertion Sort)。
 *
 * @author 创想编程(TOPPHP.ORG)
 * @copyright Copyright (c) 2013 创想编程(TOPPHP.ORG) All Rights Reserved
 * @license http://www.opensource.org/licenses/mit-license.php MIT LICENSE
 * @version 1.0.0 - Build20130613
 */
class InsertionSort {
  /**
   * 需要排序的数据数组。
   *
   * @var array
   */
  private $data;
 
  /**
   * 数据数组的长度。
   *
   * @var integer
   */
  private $size;
 
  /**
   * 数据数组是否已排序。
   *
   * @var boolean
   */
  private $done;
 
  /**
   * 构造方法 - 初始化数据。
   *
   * @param array $data 需要排序的数据数组。
   */
  public function __construct(array $data) {
    $this->data = $data;
    $this->size = count($this->data);
    $this->done = FALSE;
  }
 
  /**
   * 插入排序。
   */
  private function sort() {
    $this->done = TRUE;
 
    for ($i = 1; $i < $this->size; ++$i) {
      $current = $this->data[$i];
 
      if ($current < $this->data[$i - 1]) {
        for ($j = $i - 1; $j >= 0 && $this->data[$j] > $current; --$j) {
          $this->data[$j + 1] = $this->data[$j];
        }
 
        $this->data[$j + 1] = $current;
      }
    }
  }
 
  /**
   * 获取排序后的数据数组。
   *
   * @return array 返回排序后的数据数组。
   */
  public function getResult() {
    if ($this->done) {
      return $this->data;
    }
 
    $this->sort();
 
    return $this->data;
  }
}
?>

示例代码 1
2
3
4 <?php
$insertion = new InsertionSort(array(9, 1, 5, 3, 2, 8, 6));
echo '<pre>', print_r($insertion->getResult(), TRUE), '</pre>';
?>

  推荐精品文章

·2024年12月目录 
·2024年11月目录 
·2024年10月目录 
·2024年9月目录 
·2024年8月目录 
·2024年7月目录 
·2024年6月目录 
·2024年5月目录 
·2024年4月目录 
·2024年3月目录 
·2024年2月目录 
·2024年1月目录
·2023年12月目录
·2023年11月目录

  联系方式
TEL:010-82561037
Fax: 010-82561614
QQ: 100164630
Mail:gaojian@comprg.com.cn

  友情链接
 
Copyright 2001-2010, www.comprg.com.cn, All Rights Reserved
京ICP备14022230号-1,电话/传真:010-82561037 82561614 ,Mail:gaojian@comprg.com.cn
地址:北京市海淀区远大路20号宝蓝大厦E座704,邮编:100089