维基百科

C++实现

适用于整形和浮点型。

1
2
3
4
5
6
7
8
template<typename T>
void bubble_sort(T arr[], int len) {
4int i, j;
4for (i = 0; i < len - 1; i++)
44for (j = 0; j < len - 1 - i; j++)
444if (arr[j] > arr[j + 1])
4444std::swap(arr[j], arr[j + 1]);;
}

Python

1
2
3
4
5
6
7
8
def bubble_sort(iterable):
sorting = list(iterable)
length = len(sorting)
for i in range(length -1):
for j in range(length - 1, i, -1):
if sorting[j] < sorting[j - 1]:
sorting[j], sorting[j - 1] = sorting[j - 1], sorting[j]
return sorting

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
Array.prototype.bubble_sort = function(){
4var i,j,temp;
4for(i=0;i<this.length -1;i++)
44for(j=0;j<this.length -1 -i;i++){
444if(this[j]>this[j+1]){
4444temp=this[j];
4444this[j]=this[j+1];
4444this[j+1]=temp;
444}
44}
4return this;
};