1. 程式人生 > >python實現冒泡和快排演算法

python實現冒泡和快排演算法

#!/usr/bin/python
# -*- coding:utf-8 -*-

def bubble_sort(seq):
    # 氣泡排序
    count = len(seq)
    for i in range(0, count):
        for j in range(i + 1, count):
            if seq[i] > seq[j]:
                seq[i], seq[j] = lists[j], lists[i]
    return lists

def qsort(seq):
    if seq==[]:
        return []
    else:
        pivot=seq[0]
        lesser=qsort([x for x in seq[1:] if x<pivot])
        greater=qsort([x for x in seq[1:] if x>=pivot])
        return lesser+[pivot]+greater
 
if __name__=='__main__':
    seq=[5,6,78,9,0,-1,2,3,-65,12]
    print(qsort(seq))
    print(bubble_sort(seq))
  
輸出:
[-65, -1, 0, 2, 3, 5, 6, 9, 12, 78]
[-65, -1, 0, 2, 3, 5, 6, 9, 12, 78]