冒泡排序python
2016-01-14 15:46
253 查看
冒泡排序:从第一个数开始,依次比较后面的数,比较大小,然后交换位置,循环第一个数++,知道全部比较晚。效率:O(n2)
如下:
结果:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
c++ 实现:
结果:0 1 2 3 4 5 6 7 8 9
如下:
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
相关文章推荐
- python向mysql数据库插入数据处理特殊字符
- python requests库入门[转]
- Python获取主机名
- Python语法备忘
- python操作mysql数据库
- python操作MySQL数据库
- python 写 yml文件
- python 之编码问题详解
- [Python] MySQLdb(即 MySQL-python 包)在 OS X 中安装指南
- python 计算器
- 5种Python单例模式的实现方式
- python练手基础
- python常用函数 time.strftime
- Python读写文件
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- python操作MySQL数据库
- python学习----------面向对象1
- Python JSON模块
- Python - abs vs fabs
- Python之路【第二篇】:Python基础(二)