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

勺顛顛發表於2019-08-14

思路:每次插入資料時均和前面的資料做比較,一直找到合適的插入位置。

要排序的資料:
Array
(
    [0] => Person Object
        (
            [id] => 23
            [data] => 勺顛顛
        )

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

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

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

    [4] => Person Object
        (
            [id] => 4
            [data] => 肥嘟嘟
        )

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

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

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

)
按物件的id升序排序
<?php
/**
 * Created by PhpStorm.
 * User: 1655664358@qq.com
 * Date: 2018/8/14
 * Time: 09:08
 */
class Person
{
    public $id;
    public $data;
}

function insertSort(&$data,$n)
{
    for ($i=1;$i<$n;$i++){
        if ($data[$i]->id<$data[$i-1]->id){
            $j = $i-1;
            $x = $data[$i]->id;
            $obj = $data[$i];
            while($j>-1&&$x<@$data[$j]->id){
                $data[$j+1] = $data[$j];
                $j--;

            }
            $data[$j+1] = $obj;
        }
    }
}
(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);

})();

相關文章