Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Heap(object):
- def __init__(self, A):
- self._data = A
- self._size = len(A)
- self._build()
- def _build(self):
- m = (len(self._data) - 1) // 2
- for i in xrange(m, -1, -1):
- self._heapify(i)
- def _heapify(self, i):
- left = 2*i + 1
- right = 2*i + 2
- if left < self._size and self._data[left] > self._data[i]:
- max = left
- else:
- max = i
- if right < self._size and self._data[right] > self._data[max]:
- max = right
- if max != i:
- t = self._data[max]
- self._data[max] = self._data[i]
- self._data[i] = t
- self._heapify(max)
- def heapSort(self):
- n = len(self._data) - 1
- for i in xrange(n, 0, -1):
- t = self._data[0]
- self._data[0] = self._data[i]
- self._data[i] = t
- self._size -= 1
- self._heapify(0)
- heap = Heap([1,5,8,9,4,3,2])
- print heap._data
- heap.heapSort()
- print heap._data
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement