Advertisement
Guest User

Untitled

a guest
Jul 19th, 2021
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. def max_heapify(tree, n, i):
  2.     larger = i
  3.     left = 2 * i + 1
  4.     right = 2 * i + 2
  5.  
  6.     # with left < n and right < n we check whether there is a 'left' and 'right' child of the current node
  7.     if left < n and tree[left] > tree[larger]:
  8.         larger = left
  9.     if right < n and tree[right] > tree[larger]:
  10.         larger = right
  11.  
  12.     if larger != i:
  13.         tree[i], tree[larger] = tree[larger], tree[i]
  14.         max_heapify(tree, n, larger)
  15.         # yield tree, i, (None, ), larger # why yielding here gives weird outputs
  16.  
  17. def heap_sort(array):
  18.     n = len(array)
  19.     # create a heap data structure from the given array
  20.     for i in range(n // 2, -1, -1):
  21.         max_heapify(array, n, i)
  22.     # actual heap sort logic
  23.     for i in range(n-1, 0, -1):
  24.         array[i], array[0] = array[0], array[i]
  25.         max_heapify(array, i, 0)
  26.         yield array, i, (None,), 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement