algorithm-php
algorithm-php copied to clipboard
更好的理解建议
/**
- BubbleSort
- 冒泡排序,依次比较相邻的两个元素的大小,如果前面的大于后面的,那么交换两者位置
- @param array $container
- @return array */ function BubbleSort(array $container) { $count = count($container); for ($j = 1; $j < $count; $j++) { for ($i = 0; $i < $count - $j; $i++) { if ($container[$i] > $container[$i + 1]) { $temp = $container[$i]; $container[$i] = $container[$i + 1]; $container[$i + 1] = $temp; } } $str = "第" . $j . "步排序结果"; $res = $str . implode(',', $container); printf("%s\n",$res); } return $container; }
BubbleSort([4, 21, 41, 2, 53, 1, 213, 31, 21, 423]);
/* 第1步排序结果4,21,2,41,1,53,31,21,213,423 第2步排序结果4,2,21,1,41,31,21,53,213,423 第3步排序结果2,4,1,21,31,21,41,53,213,423 第4步排序结果2,1,4,21,21,31,41,53,213,423 第5步排序结果1,2,4,21,21,31,41,53,213,423 第6步排序结果1,2,4,21,21,31,41,53,213,423 第7步排序结果1,2,4,21,21,31,41,53,213,423 第8步排序结果1,2,4,21,21,31,41,53,213,423 第9步排序结果1,2,4,21,21,31,41,53,213,423 */
欢迎提交Pr