バブルソートJavaとPythonの書き方比較


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 sort

	public 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.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
str = "zbac"
print(bubble(str)) # ['a', 'b', 'c', 'z']
number=[16,134,15,1]
print(bubble(number)) # [1, 15, 16, 134]