バブルソート(bubble sort)もやってみた。
import random def bubble_sort(lis): l = range(1, len(lis)) l.reverse() for i in l: for j in range(1, i+1): if lis[j-1] > lis[j]: lis[j], lis[j-1] = lis[j-1], lis[j] return lis l = range(1,10) * 2 random.shuffle(l) print "unsorted:", l l2 = bubble_sort(l) print "sorted: ", l2
実行結果:
^o^ > python bubble_sort.py unsorted: [7, 6, 8, 2, 1, 4, 2, 6, 8, 3, 4, 5, 9, 9, 3, 5, 7, 1] sorted: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]