选择排序

/**
 * 选择排序
 */

function findSmallest($list)
{
    $small = $list[0];
    $k = 0;
    foreach ($list as $key => $value) {
        if ($value <= $small) {
            $small = $value;
            $k = $key;
        }
    }
    return $k;
}

function selectionSort($list)
{
    $arr = [];
    $num = count($list);
    for ($i = 0; $i < $num; $i++) {
        $smallestKey = findSmallest($list);
        $arr[] = $list[$smallestKey];
        unset($list[$smallestKey]);
        $list = array_values($list);

    }
    return $arr;
}
posted @ 2022-03-17 13:03  不当病猫  阅读(16)  评论(0)    收藏  举报