排序演算法:插入折半排序 PHP 版

勺顛顛發表於2019-08-16

仍然是對插入排序演算法的改進,增加了折半演算法,主要是減少資料的移動次數,和折半查詢演算法是一個思想。

<?php
/**
 * Created by PhpStorm.
 * User: 1655664358@qq.com
 * Date: 2018/6/14
 * Time: 10:08
 */
class Person
{
    public $id;
    public $data;
}

function insertSort(&$data,$n)
{
    for ($i=1;$i<$n;$i++){
        $low = 0;
        $high = $i-1;
        $temp = $data[$i];
        while ($low<=$high){
            $mid = floor(($low+$high)/2);
            if ($data[$mid]->id>$temp->id){
                $high = $mid-1;
            }else{
                $low = $mid+1;
            }
        }
        for ($j=$i;$j>$low;$j--){
            $data[$j] = $data[$j-1];
        }
        $data[$low] = $temp;
    }
}
(function(){

    $person = new Person();
    $index = ['23'=>'勺顛顛','65'=>'老油條','21'=>'燒包穀','9'=>'燒耳塊','4'=>'肥嘟嘟','7'=>'黴戳戳','32'=>'一坨肉','6'=>'老扎哇'];
    $data = [];
    foreach ($index as $k=>$v){
        $obj = clone $person;
        $obj->id = $k;
        $obj->data = $v;
        $data[] = $obj;
    }

    insertSort($data,8);
    print_r($data);

})(); 
結果: 
Array
(
    [0] => Person Object
        (
            [id] => 4
            [data] => 肥嘟嘟
        )

    [1] => Person Object
        (
            [id] => 6
            [data] => 老扎哇
        )

    [2] => Person Object
        (
            [id] => 7
            [data] => 黴戳戳
        )

    [3] => Person Object
        (
            [id] => 9
            [data] => 燒耳塊
        )

    [4] => Person Object
        (
            [id] => 21
            [data] => 燒包穀
        )

    [5] => Person Object
        (
            [id] => 23
            [data] => 勺顛顛
        )

    [6] => Person Object
        (
            [id] => 32
            [data] => 一坨肉
        )

    [7] => Person Object
        (
            [id] => 65
            [data] => 老油條
        )

)

相關文章