简体   繁体   English

为什么下面的heapsort函数不会产生错误

[英]Why doesn't the following heapsort function produce an error

I took the following code from GeeksforGeeks to try and understand heap sort 我从GeeksforGeeks中获取了以下代码,以尝试了解堆排序

def heapify(arr, n, i): 
    largest = i 
    l = 2*i + 1     
    r = 2*i + 2    
    if l < n and arr[i] < arr[l]: 
        largest = l 
    if r < n and arr[largest] < arr[r]: 
        largest = r 
    if largest != i: 
        arr[i],arr[largest] = arr[largest],arr[i] 
        heapify(arr, n, largest) 

def heapSort(arr): 
    n = len(arr)
    for i in range(n, -1, -1): 
        heapify(arr, n, i) 
    for i in range(n-1, 0, -1): 
        arr[i], arr[0] = arr[0], arr[i] 
        heapify(arr, i, 0) 

arr = [7, 11, 13, 6, 5, 12] 
heapSort(arr) 

print ("Sorted array is", arr) 

On the very first iteration, n = 6 and l = 13 Then for the following line of code 在第一次迭代中,n = 6且l = 13然后是下面的代码行

if l < n and arr[i] < arr[l]

arr[l] points to an index that doesn't exist. arr [l]指向不存在的索引。

I don't understand why this doesn't flag an error like "out of index" or something. 我不明白为什么这不标记“索引不足”之类的错误。 Even though its an "if" statement, it is still surely checking the value in arr[l]. 即使其为“ if”语句,它仍肯定会检查arr [l]中的值。 As this doesn't exist, it should "break" and flag an error? 由于不存在,因此应该“中断”并标记错误?

Thanks 谢谢

if-statement conditions are evaluated in the order that they are defined. if语句条件按照定义的顺序进行评估。 they are also optimized. 他们也进行了优化。

if l < n and arr[i] < arr[l]

The l < n will be evaluated first. l < n将首先被评估。 It's False . False Since and ing anything with False will be false anyway, the arr[i] < arr[l] is never evaluated. 由于and以1ng任何False将是假的反正arr[i] < arr[l]是从来没有进行评价。 Hence you never get the IndexError 因此,您永远不会得到IndexError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM