てんてー

~Web開発の備忘録~

バブルソートをPHPでやってみる

sort.php

<?php

/*

 * bubble sort

 */
$sauce = $argv;
$cut_number = 0;

$check_with = null;
echo to_sort($sauce, $cut_number, $check_with);

function to_sort($sauce, $cut_number, $check_with)  {
$count = count($sauce);

if ($cut_number < $count - 1) {

$value = $sauce[$cut_number];

$next_value = $sauce[$cut_number + 1];
if ($value > $next_value) {

$sauce[$cut_number] = $next_value;

$sauce[$cut_number + 1] = $value;

$check_with = 1;

}

}
if ($cut_number === $count) {

if (isset($check_with)) {

$cut_number = 0;

$check_with = null;
return to_sort($sauce, $cut_number, $check_with);

}

return implode($sauce);

}
$cut_number = $cut_number + 1;
return to_sort($sauce, $cut_number, $check_with);

 

 このブログ、コード載せるの相応しくないな

 

群馬の山奥生活でやることがないので、配列をバブルソートアルゴリズムで昇順にソートするプログラムをPHPで書いてみました。

 コマンドプロンプトで以下のように入力して実行すると、ソート結果が出力されます。

sort.php 引数1 引数2 引数3... 

 半角スペースで区切って数字を入力すれば配列になります。

→ array(引数1, 引数2, 引数3);

 

結果

f:id:takahashikareha:20180813141639p:plain

あ、出力は配列じゃなくて文字列です