冒泡,快排,堆排序

 

 

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = "ligq"
import time
import random
import copy
import sys

def cal_time(func):
    def wrapper(*args, **kwargs):
        t1 = time.time()
        result = func(*args, **kwargs)
        t2 = time.time()
        print("%s running time: %s secs." % (func.__name__, t2 - t1))
        return result
    return wrapper


#构造堆
def sift(data,low ,high):
    i = low
    j = 2 * i + 1
    tmp = data[i]
    while j <= high:
        if j+1 <= high and data[j] < data[j +1]:
            j += 1
        if data[j] >tmp:
            data[i] = data[j]
            i = j
            j = 2*i+1
        else:
            break
    data[i]=tmp

#堆排序
@cal_time
def heap_sort(data):
    n = len(data)
    for i in range (n // 2 -1,-1,-1):
        sift(data,i ,i -1)
    for i in range(n-1,-1,-1):
        data[0],data[i] = data[i],data[0]
        sift(data,0,i-1)


#冒泡排序
@cal_time
def bubble_sort(data):
    for i in range(len(li)-1):
        exchange = False
        for j in range(len(li) - i- 1):
            if li[j] > li [j+1]:
                li[j],li[j+1] = li[j+1],li[j]
                exchange =True
        if not exchange:
            break





li = list(range(100))

# random.shuffle(li)
print(li)
bubble_sort(li)
print(li)
# random.shuffle(li)
print(li)
heap_sort(li)
print(li)

 

posted @ 2017-03-17 11:25  noube  阅读(233)  评论(0编辑  收藏  举报