PHPで バブルソート (bubble sort)のサンプルコード

phpコード:
<?php

$arr1=array(1,-1,10,-9,0,3,7,-20,100);

function Sort1($arr){
for ($i=0;$i<count($arr)-1;$i++){

for ($j=0;$j<count($arr)-1-$i;$j++){

if ($arr[$j]>$arr[$j+1]){
$temp=$arr[$j];
$arr[$j]=$arr[$j+1];
$arr[$j+1]=$temp;

}
}
}
return $arr;
}

$brr=Sort1($arr1);
print_r($brr);

$j=0;

for ($i=count($brr)-1;$i>=0;$i–){
$crr[$j]=$brr[$i];
$j++;

}
print_r($crr);
?>
[root@startnews24]# php sort1.php
Array
(
[0] => -20
[1] => -9
[2] => -1
[3] => 0
[4] => 1
[5] => 3
[6] => 7
[7] => 10
[8] => 100
)
Array
(
[0] => 100
[1] => 10
[2] => 7
[3] => 3
[4] => 1
[5] => 0
[6] => -1
[7] => -9
[8] => -20
)

PHP

Posted by arkgame