冒泡排序python
冒泡排序:从第一个数开始,依次比较后面的数,比较大小,然后交换位置,循环第一个数++,知道全部比较晚。效率:O(n2)
如下:
def bubble_sort(lists):
count = len(lists)
for i in range(0, count):
for j in range(i + 1, count):
if lists[i] > lists[j]:
lists[i], lists[j] = lists[j], lists[i]
return lists
if __name__ == '__main__':
lists = [3,1,2,6,9,8,4,7,5,0]
ret = bubble_sort(lists)
print ret
结果:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
c++ 实现:
#include<iostream>
#include<stdio.h>
using namespace std;
int main(int argc,char* argv[])
{
int lists[10] = {5,3,8,6,9,2,1,4,7,0};
int count = sizeof(lists)/sizeof(int);
for(int i=0;i<count;i++){
for(int j=i+1;j<count;j++){
int temp;
if(lists[i] > lists[j]){
temp = lists[i];
lists[i] = lists[j];
lists[j] = temp;
}
}
}
for(int i=0;i<count;i++){
cout<<lists[i]<<" ";
}
printf("\n");
return 0;
}
结果:0 1 2 3 4 5 6 7 8 9
浙公网安备 33010602011771号