0
0

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でソートと解説を書いてみた

Posted at
bubble_sort.php
<?php
$numbers = array(1,3,5,4,2);
// バブルソート

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

function bubble_sort($array)
{
  // 配列の要素以下の回数繰り返し処理を行う
    for($i = 0; $i < count($array); $i++)
    {
      // 一列分行うから1個目のfor文の中へ
        for($n = 1; $n < count($array); $n++)
        {
          // 1つ目の要素と、その次の要素を比較して、1つめが大きい場合
            if($array[$n-1] > $array[$n])
            {
              // $temp_numberに小さい方の数字を保存
                $temp_number = $array[$n];
              // 大きかった位置に、正しい小さな数字を挿入
                $array[$n] = $array[$n-1];
              // 大きい方の数字を、本来正しい位置に挿入
                $array[$n-1] = $temp_number;
            }
        }
    }
    return $array;
}
0
0
0

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?