python实现冒泡排序和快速排序

冒泡排序和快排的python实现:


data = [1, 3, 5, 10, 4, 7]
times = 0
"冒泡排序"
for i in range(len(data)):
    for j in range(len(data) - i - 1):
        if data[j] > data[j + 1]:
            tmp = data[j + 1]
            data[j + 1] = data[j]
            data[j] = tmp
        times += 1

print("冒泡排序")
print(data)
print("times:%d" % times)


"改进冒泡排序,插入标志位,提前结束排序"
data = [1, 3, 5, 10, 4, 7]
times = 0
for i in range(len(data)):
    pos = 0
    for j in range(len(data) - i - 1):
        if data[j] > data[j + 1]:
            tmp = data[j + 1]
            data[j + 1] = data[j]
            data[j] = tmp
            pos = 1
        times += 1
    if pos == 0:
        break

print("改进冒泡排序")
print(data)
print("times:%d" % times)


"快排,选第一个数为基准值,小数放在基准左边,大数放在基准右边"
data = [1, 3, 5, 10, 4, 7]


def exchage(x, y):
    return y, x


def qsort(left , right):
    if left > right:
        return
    p = data[left]
    i = left
    j = right

    while i != j:
        

        while data[j] > p and i < j:
            j -= 1

        data[i],data[j] = exchage(data[i],data[j])

        while data[i] < p and i < j:
            i += 1
        
        data[i],data[j] = exchage(data[i],data[j])

    
    qsort(left,i-1)
    qsort(i+1,right)
    

qsort(0,len(data)-1)
print("quick sort")
print(data)

输出结果:

冒泡排序
[1, 3, 4, 5, 7, 10]
times:15
改进冒泡排序
[1, 3, 4, 5, 7, 10]
times:12
quick sort
[1, 3, 4, 5, 7, 10]
posted @ 2017-04-08 18:41  Weyne  阅读(666)  评论(0编辑  收藏  举报