排序

#!/usr/bin/envpython
#-*-coding:utf-8-*-
import time,random

def heap_sort(lst):
    for start in range((len(lst)-2)/2,-1,-1):
        sift_down(lst,start,len(lst)-1)

    for end in range(len(lst)-1,0,-1):
        lst[0],lst[end]=lst[end],lst[0]
        sift_down(lst,0,end-1)
    return lst

def sift_down(lst,start,end):
    root=start
    while True:
        child=2*root+1
        if child>end:
            break
        if child+1<=end and lst[child]<lst[child+1]:
            child+=1
        if lst[root]<lst[child]:
            lst[root],lst[child]=lst[child],lst[root]
            root=child
        else:
            break


def bubble(bubbleList):
    listLength=len(bubbleList)
    while listLength>0:
        for i in range(listLength-1):
            if bubbleList[i]>bubbleList[i+1]:
                bubbleList[i]=bubbleList[i]+bubbleList[i+1]
                bubbleList[i+1]=bubbleList[i]-bubbleList[i+1]
                bubbleList[i]=bubbleList[i]-bubbleList[i+1]
        listLength-=1
    return bubbleList

def main():
    #l=[9,2,32,4,1,7,6,8,5,43,76,87,33,3,4]
    l = []
    for i in range(10000,0,-1):
        l.append(i)
    random.shuffle(l)

file = open("l.txt",'w')
    file.write(str(l))
    file.close
    time_begin = time.clock()
    #print 'heap_sort =  ' + str(heap_sort(l))
    A = heap_sort(l)                            #堆排序
    file = open("A.txt",'w')
    file.write(str(A))
    file.close
    print "time use %s" % (time.clock() - time_begin)
    time_begin = time.clock()
    #print 'bubble =   ' + str(bubble(l))
    B = bubble(l)                                #冒泡排序
    file = open("B.txt",'w')
    file.write(str(B))
    file.close
    print "time use %s" % (time.clock() - time_begin)

if __name__=="__main__":
    main()



[root@localhost tmp]# python sort.py
time use 0.2
time use 7.89

冒泡排序的时间长很多

你可能感兴趣的:(排序)