1

我正在尝试使用Intro to Algorithms一书中的伪代码来实现堆排序。以下是我所拥有的:

def parent(i):
    return i/2

def left(i):
    return 2*i

def right(i):
    return 2*i+1

def max_heapify(seq, i, n):
    l = left(i)
    r = right(i)

    if l <= n and seq[n] > seq[i]:
        largest = l
    else:
        largest = i
    if r <= n and seq[r] > seq[largest]:
        largest = r

    if largest != i:
        seq[i], seq[largest] = seq[largest], seq[i]
        max_heapify(seq, largest, n)

def heap_length(seq):
    return len(seq) - 1

def build_heap(seq):
    n = heap_length(seq)
    for i in range(n/2,0,-1):
        max_heapify(seq, i, n)

def sort(seq):
    build_heap(seq)
    heap_size = heap_length(seq)
    for i in range(heap_size,1,-1):
        seq[1], seq[i] = seq[i], seq[1]
        heap_size = heap_size - 1
        max_heapify(seq, 1, heap_size)

    return seq

我在理解 Python 中的值传递或引用传递时遇到问题。我查看了以下问题,似乎我正在按值传递列表。我的问题是如何通过引用或值返回正确排序的列表?

4

1 回答 1

2

如果要按值传递,则数组始终按引用传递,请使用切片

my_func(my_array[:])#发送副本

my_func(my_array) #array is modified inside and changes are reflected in original

于 2012-08-28T23:47:33.640 回答