简体   繁体   中英

Why doesn't the following heapsort function produce an error

I took the following code from GeeksforGeeks to try and understand heap sort

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

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

arr[l] points to an index that doesn't exist.

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]. 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. they are also optimized.

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

The l < n will be evaluated first. It's False . Since and ing anything with False will be false anyway, the arr[i] < arr[l] is never evaluated. Hence you never get the IndexError

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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