0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【挿入ソート】PHPでソートと解説を書いてみた

Last updated at Posted at 2020-11-06

ご紹介

PHP で挿入ソートを書いてみました。
バブルソートもこちらで解説しています。

挿入ソートって何よ?って方にはコチラ
多重代入などすることでコード量をもう少し短く書ける気がします。
解説はコメントに書きました。

是非アドバイスお願いします。

<?php
$numbers = array(1,3,5,4,2,6);
// 挿入ソート

// 出力
var_dump(insertion_sort($numbers));

function insertion_sort($array)
{
    // 配列の要素の数だけ繰り返し処理を行う
    for ($i = 1; $i < count($array); $i++) {
        // 比較する数字【$new_number】とその1個前の数字(比較される数字)の場所を保存する【$old_number_position】を作成
        $new_number = $array[$i];
        $old_number_position = $i - 1;

        // 一番左端に$old_number_positionが行くまで繰り返す
        while ($old_number_position > 0) {
            // 比較する数字が、される数字より小さかった場合、入れ替える
            if ($new_number < $array[$old_number_position]) {
                $temp_number = $array[$old_number_position];
                $array[$old_number_position] = $array[$old_number_position + 1];
                $array[$old_number_position + 1] = $temp_number;
            }
            // 比較される数字を一個左にずらす
            $old_number_position -= 1;
            // ※数字が動く様子を見ることができます。
            print_r($array);
        }
    }
    return $array;
}
0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?