通过实现堆排序的递归传递值或引用

时间:2012-08-28 23:43:05

标签: python algorithm recursion

我正在尝试使用书籍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中的值传递或引用时遇到了问题。我查看了以下question,似乎我按值传递列表。我的问题是如何通过引用或值返回正确排序的列表?

1 个答案:

答案 0 :(得分:2)

数组总是通过引用传递 如果你想通过值传递使用切片

my_func(my_array[:]) #send copy

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