zoukankan      html  css  js  c++  java
  • php 排序算法 堆排序

    abstract class HeapSort{
    protected $count;
    protected $data;
    public function __construct(array $data)
    {
    $this->count = count($data);
    $this->data = $data;
    }
    public function run()
    {
    $this->createHeap();
    while ($this->count > 0) {
    $this->swap($this->data[0], $this->data[--$this->count]);
    $this->buildHeap($this->data, 0, $this->count);
    }
    return $this->data;
    }
    public function createHeap()
    {
    $i = floor($this->count / 2) + 1;
    while ($i--) {
    $this->buildHeap($this->data, $i, $this->count);
    }
    }
    public function swap(&$left, &$right)
    {
    list($left, $right) = array ($right, $left);
    }

    abstract public function buildHeap(array &$data, $i, $count);
    }

    class HeapMaxSort extends HeapSort
    {
    public function buildHeap(array &$data, $i, $count)
    {
    if (false === $i < $count) {
    return;
    }
    $right = ($left = 2 * $i + 1) + 1;
    $max = $i;
    if ($left < $count && $data[$i] < $data[$left]) {
    $max = $left;
    }
    if ($right < $count && $data[$max] < $data[$right]) {
    $max = $right;
    }
    if ($max !== $i && $max < $count) {
    $this->swap($data[$i], $data[$max]);
    $this->buildHeap($data, $max, $count);
    }
    }
    }
    class HeapMinSort extends HeapSort{
    public function buildHeap(array &$data,$i,$count){

    if (false === $i < $count) {
    return;
    }

    $right = ($left = 2 * $i + 1) + 1;
    $min = $i;

    if($left < $count && $data[$i] > $data[$left]){
    $min = $left;
    }

    if($right < $count && $data[$min] > $data[$right]){
    $min = $right;
    };
    if($min < $count && $min != $i){
    $this->swap($data[$i], $data[$min]);
    $this->buildHeap($data, $min, $count);
    }
    }
    }
    $array = array (4, 21, 41, 2, 53, 1, 213, 31, 21, 423, 56);
    $result = (new HeapMinSort($array))->run();
    $result1 = (new HeapMaxSort($array))->run();
    print_r($result);
    print_r($result1);

    引用自 https://github.com/PuShaoWei/arithmetic-php,在这个基础上重构了一个从大到小的排序

  • 相关阅读:
    H5C3--transform实现任何元素居中对齐
    H5C3--过渡transition
    H5C3--background中cover,背景样式,提升响应区域+精灵图的使用
    SpringBoot之spring.factories
    浅谈常用数据结构
    浅谈常用排序
    JAVA性能优化总结
    ORACLE10G非归档模式下RMAN异机迁库
    ORACLE10G非归档模式下异机迁库(文件迁移)
    HNOI 米特运输
  • 原文地址:https://www.cnblogs.com/hubudong/p/9811202.html
Copyright © 2011-2022 走看看