def bubble(arr)
(arr.length-1).downto(1) do |j|
a1 = arr.dup
j.times do |i|
if arr > arr[i+1]
arr,arr[i+1] = arr[i+1],arr
end
end
break if a1 == arr
end
arr
end
Java
static void BubbleSort(int a []){
int temp=0;
for (int i = 0; i < a.length-1 ; i++) {
for (int j = 0; j < a.length - i - 1; j++){
if (a[j]>a[j + 1]){ //把這裏改爲大於,就是升序了
temp=a[j];
a[j]=a[j + 1];
a[j + 1]=temp;
}
}
}
}
Visual Basic
Option Explicit
Private Sub Form_click()
Dim a, c As Variant
Dim i As Integer, temp As Integer, w As Integer
a = Array(12, 45, 17, 80, 50)
For i = 0 To UBound(a) - 1
If (a(i) > a(i + 1)) Then '如果遞減,改成a(i)<a(i+1)
temp = a(i)
a(i) = a(i + 1)
a(i + 1) = temp
End If
Next
For Each c In a
Print c;
Next
End Sub
Pascal
<i id="bks_9tjbxut2">program bubblesort;
const
N=20;
MAX=10;
var
a:array[1..N] of 1..MAX;
temp,i,j:integer;
begin
randomize;
for i:=1 to N do a:=1+random(MAX);
writeln('Array before sorted:');
for i:=1 to N do write(a,' ');
writeln;
for i:=N-1 downto 1 do
for j:=1 to i do
if a[j]<a[j+1] then
begin
temp:=a[j];
a[j]:=a[j+1];
a[j+1]:=temp
end;
writeln('Array sorted:');
for i:=1 to N do write(a,' ');
writeln;
writeln('End sorted.');
readln;
end.
C#
public void BubbleSort(int[] array) {
int length = array.Length;
for (int i = 0; i <= length - 2; i++) {
for (int j = length - 1; j >= 1; j--) {
if (array[j] < array[j - 1] ) {
int temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
}
}
}
}
Python
#BubbleSort used python3.1 or python 2.x
def bubble(str):
tmplist = list(str)
count = len(tmplist)
for i in range(0,count-1):
for j in range(0,count-1):
if tmplist[j] > tmplist[j+1]:
tmplist[j],tmplist[j+1] = tmplist[j+1],tmplist[j]
return tmplist
#useage:
str = "zbac"
print(bubble(str)) # ['a', 'b', 'c', 'z']
number=[16,134,15,1]
print(bubble(number)) # [1, 15, 16, 134]