php 实现
<?php
function bubbleSort($list)
{
$count = count($list);
for ($i = 0; $i < $count - 1; $i++) {
for ($j = 0; $j < $count - 1 - $i; $j++) {
if ($list[$j] > $list[$j + 1]) {
$tem = $list[$j];
$list[$j] = $list[$j + 1];
$list[$j + 1] = $tem;
}
}
}
return $list;
}
$list = [1, 5, 3, 5, 8, 9];
var_dump(bubbleSort($list));
golang 实现
从小到大排
func maoPao(arr []int) []int {
length := len(arr)
for i := 0; i < length-1; i++ {
for j := 0; j < length-i-1; j++ {
if arr[j] > arr[j+1] {
tmp := arr[j]
arr[j] = arr[j+1]
arr[j+1] = tmp
}
}
}
return arr
}
从大到小排
func maoPaoV2(arr []int) []int {
length := len(arr)
for i := 0; i < length-1; i++ {
for j := 0; j < length-i-1; j++ {
if arr[j] < arr[j+1] {
tmp := arr[j]
arr[j] = arr[j+1]
arr[j+1] = tmp
}
}
}
return arr
}