Java 版本
package com.stephen;
public class BubbleSort {
public static void main(String[] args) {
int[] a = {2,5,4,1,7,2,3};
int[] sortedA = bubbleSort(a, "DESc");
for (int i = 0; i < sortedA.length; i ++) {
System.out.println(sortedA[i]);
}
}
public static int[] bubbleSort(int[] array, String sortType) {
if (array.length <= 1) {
return array;
}
for (int i = 0; i < array.length; i ++) {
for (int j = array.length - 1; j > i; j --) {
boolean flag = true;
if ("DESC".equals(sortType.toUpperCase())) {
flag = array[j] > array[j - 1];
} else {
flag = array[j] < array[j - 1];
}
if (flag) {
int temp = array[j];
array[j] = array[j - 1];
array[j-1] = temp;
}
}
}
return array;
}
}
PHP
<?php
function bubbleSort($array, $sort_type = 'ASC')
{
$length = count($array);
if ($length <= 1) {
return $array;
}
for ($i = 0; $i < $length; $i++) {
for ($j = $length - 1; $j > $i; $j--) {
if ('DESC' == strtoupper($sort_type)) {
$flag = $array[$j] > $array[$j - 1];
} else {
$flag = $array[$j] < $array[$j - 1];
}
if ($flag) {
$temp = $array[$j];
$array[$j] = $array[$j - 1];
$array[$j - 1] = $temp;
}
}
}
return $array;
}
$array = array(1,4,2,6,3,4,9,0,2,1);
$array = bubbleSort($array);
echo var_dump($array);