You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
heap_size=0# global variabledefleft(i):
return2*i+1defright(i):
return2*i+2defmax_heapify(arr, i):
globalheap_size# Access the global heap sizeleft_child_index=left(i)
right_child_index=right(i)
largest=i# Check if the left child exists and is greater than the current nodeifleft_child_index<heap_sizeandarr[left_child_index] >arr[largest]:
largest=left_child_index# Check if the right child exists and is greater than the current largestifright_child_index<heap_sizeandarr[right_child_index] >arr[largest]:
largest=right_child_index# If the largest is not the current node, swap and continue heapifyingiflargest!=i:
arr[i], arr[largest] =arr[largest], arr[i]
max_heapify(arr, largest)
defbuild_max_heap(arr):
globalheap_sizeheap_size=len(arr) # Set the global heap size for the entire build process# Start from the last non-leaf node and go up to the rootforiinrange((heap_size//2) -1, -1, -1):
max_heapify(arr, i)
defHeapSort(arr):
globalheap_sizebuild_max_heap(arr)
# Repeatedly extract the max element and rebuild the heapforiinrange(len(arr) -1, 0, -1):
arr[0], arr[i] =arr[i], arr[0] # Swap the root (max element) with the last elementheap_size-=1# Reduce the size of the heapmax_heapify(arr, 0) # Restore the heap propertyarr= [3, 6, 1, 8, 12, 4, 7]
HeapSort(arr)
print("Sorted array:", arr) # Sorted array: [1, 3, 4, 6, 7, 8, 12]
The text was updated successfully, but these errors were encountered:
The text was updated successfully, but these errors were encountered: