这是一种堆排序。
def Parent(i):
return i / 2
def Left(i):
return 2 * i
def Right(i):
return 2 * i + 1
def MAX_HEAPIFY(A, i): # A.heapSize == A[0]
l = Left(i)
r = Right(i)
这是问题所在。
if l <= A[0] and A[l] > A[i]:
如果我写l <= A[0] and A[l] > A[i]
,那么代码可以正确运行。
但是,如果我切换两个条件,如A[l] > A[i] and l <= A[0]
,则会出现错误。 IndexError:列表索引超出范围
largest = l
else: largest = i
if r <= A[0] and A[r] > A[largest]:
largest = r
if largest != i:
temp = A[i]
A[i] = A[largest]
A[largest] = temp
print "exchange parent %d with child %d" %(A[largest], A[i])
MAX_HEAPIFY(A, largest)
def BUILD_MAX_HEAP(A):
A[0] = len(A) - 1
for i in range(len(A) / 2, 0, -1):
MAX_HEAPIFY(A, i)
def HEAPSORT(A):
BUILD_MAX_HEAP(A)
print A
for i in range(len(A) - 1, 1, -1):
temp = A[1]
A[1] = A[i]
A[i] = temp
A[0] = A[0] - 1 # A.heapSize - 1
print "exchange parent %d with child %d the last" %(A[i], A[1])
MAX_HEAPIFY(A, 1)
感谢您的帮助。