64,654
社区成员
发帖
与我相关
我的任务
分享
def psort(l,m,n):
if m<n:
mid=int((m+n)/2);(l[m],l[mid])=(l[mid],l[m])
i=m;j=n; pk=l[m]
while i<j:
while i<j and l[j]>=pk: j-=1
l[i]=l[j]
while i<j and l[i]<pk: i+=1
l[j]=l[i]
l[i]=pk
psort(l,m,i-1); psort(l,i+1,n)
def qsort(l,m,n):
if m<n:
mid=int((m+n)/2);(l[m],l[mid])=(l[mid],l[m])
i=m+1;j=n
while i<j:
while i<j and l[m]>l[i]: i+=1
while i<j and l[m]<=l[j]: j-=1
if i<j:
(l[i],l[j])=(l[j],l[i])
i+=1; j-=1
if i==j and l[i]<l[m]: i+=1
if i-1>m: (l[i-1],l[m])=(l[m],l[i-1])
qsort(l,m,i-2); qsort(l,i,n)
def bubble(list):
flag=1
tail=len(list)-1
while(flag):
flag=0
for i in range(tail):
if list[i]>list[i+1]:
t=list[i]
list[i]=list[i+1]
list[i+1]=t
flag=1
tail-=1
def max_heapify(A,parent,heapsize):
left = 2*parent+1
right = 2*parent+2
largest = parent
if left<heapsize and A[left]>A[largest]:
largest = left
if right<heapsize and A[right]>A[largest]:
largest = right
if largest != parent:
A[parent],A[largest] = A[largest],A[parent]
max_heapify(A,largest,heapsize)
def buildHeap(A):
heapsize = len(A)
for i in range(heapsize//2-1,-1,-1):
max_heapify(A,i,heapsize)
def HeapSort(A):
heapsize = len(A)
buildHeap(A)
for i in range(len(A)-1,0,-1):
A[0],A[i] = A[i],A[0]
heapsize -= 1
max_heapify(A,0,heapsize)
def ShellSort(A):
def GetCols(n):
cols = [1]
val = 1
while val < n:
val = int(val * 2.2)
cols.insert(0, val)
return cols
for h in GetCols(len(A)):
for i in range(h, len(A)):
cur = A[i]
j = i
while j >= h and A[j - h] > cur:
A[j] = A[j - h]
j -= h
A[j] = cur
from random import random
ls=[ random() for ip in range(50000)]
g=ls[:];bp=ls[:];hp=ls[:];sh=ls[:]
from datetime import datetime
t= datetime.now(); psort(g,0,len(g)-1); h=datetime.now(); print('interval-psort is '+str(h-t))
t= datetime.now(); qsort(ls,0,len(ls)-1); h=datetime.now(); print('interval-qsort is '+str(h-t))
#t= datetime.now(); bubble(bp); h=datetime.now(); print('interval-bubble is '+str(h-t))
t= datetime.now(); HeapSort(hp); h=datetime.now(); print('interval-heapsort is '+str(h-t))
t= datetime.now(); ShellSort(sh); h=datetime.now(); print('interval-shellsort is '+str(h-t))
print('equal is',sh==ls)