六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 169|回复: 0

冒泡排序Java和Python写法比较

[复制链接]

升级  32.67%

23

主题

23

主题

23

主题

秀才

Rank: 2

积分
99
 楼主| 发表于 2013-1-19 04:06:39 | 显示全部楼层 |阅读模式
Java代码
package test;// 冒泡排序public class BubbleSort {public static void sort(Comparable[] data) {// 数组长度int len = data.length;for (int i = 0; i < len - 1; i++) {// 临时变量Comparable temp = null;// 交换标志,false表示未交换boolean isExchanged = false;for (int j = len - 1; j > i; j--) {// 如果data[j]小于data[j - 1],交换if (data[j].compareTo(data[j - 1]) < 0) {temp = data[j];data[j] = data[j - 1];data[j - 1] = temp;// 发生了交换,故将交换标志置为真isExchanged = true;}// end if}// end for// 本趟排序未发生交换,提前终止算法,提高效率if (!isExchanged) {return;}// end if}// end for}// end sortpublic static void main(String[] args) {// 在JDK1.5版本以上,基本数据类型可以自动装箱// int,double等基本类型的包装类已实现了Comparable接口Comparable[] c = { 4, 9, 23, 1, 45, 27, 5, 2 };sort(c);for (Comparable data : c) {System.out.println(data);}//for (int i=0;i<c.length;i++){//System.out.println(c);//}}} 
 Python代码
#BubbleSort used python3.1 or python 2.xdef 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 tmpliststr = "zbac"print(bubble(str)) # ['a', 'b', 'c', 'z']number=[16,134,15,1]print(bubble(number)) # [1, 15, 16, 134]  
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表