JavaScript
function bubbleSort(ary) { var i, j, temp, len = ary.length; for(var i=1; i<len; i++) { for(j=len-1; j>=i; j--) { temp = ary[j]; if(temp < ary[j-1]) { ary[j] = ary[j-1]; ary[j-1] = temp; } } } return ary; } var ary = [5,4,3,2,1]; console.log(bubbleSort(ary));
Java
public class Test {
public static void bubbleSort(int[] ary) {
int i, j, temp;
int len = ary.length;
for(i=1; i<len; i++) {
for(j=len-1; j>=i; j--) {
temp = ary[j];
if(ary[j] < ary[j-1]) {
ary[j] = ary[j-1];
ary[j-1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] ary = {5,4,3,2,1};
Test.bubbleSort(ary);
for(int it : ary) {
System.out.println(it);
}
}
}
C
#include <stdio.h> void bubbleSort(int ary[], int len) { int i, j, temp; for(i=1; i<len; i++) { for(j=len-1; j>=i; j--) { temp = ary[j]; ary[j] = ary[j-1]; ary[j-1] = temp; } } } main() { int i; int ary[] = {5,4,3,2,1}; bubbleSort(ary, 5); for(i=0; i<5; i++) { printf("%d", ary[i]); } }