MrJoe
MrJoe

Reputation: 445

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

Upvotes: 0

Views: 26

Answers (1)

rdas
rdas

Reputation: 21275

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 anding anything with False will be false anyway, the arr[i] < arr[l] is never evaluated. Hence you never get the IndexError

Upvotes: 2

Related Questions