Advertisement
DMG

Heap & heapSort

DMG
May 9th, 2014
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. class Heap(object):
  2.     def __init__(self, A):
  3.         self._data = A
  4.         self._size = len(A)
  5.         self._build()
  6.  
  7.     def _build(self):
  8.         m = (len(self._data) - 1) // 2
  9.  
  10.         for i in xrange(m, -1, -1):
  11.             self._heapify(i)
  12.  
  13.     def _heapify(self, i):
  14.         left  = 2*i + 1
  15.         right = 2*i + 2
  16.  
  17.         if left < self._size and self._data[left] > self._data[i]:
  18.             max = left
  19.         else:
  20.             max = i
  21.  
  22.  
  23.         if right < self._size and self._data[right] > self._data[max]:
  24.             max = right
  25.  
  26.         if max != i:
  27.             t = self._data[max]
  28.             self._data[max] = self._data[i]
  29.             self._data[i] = t
  30.  
  31.             self._heapify(max)
  32.  
  33.     def heapSort(self):
  34.         n = len(self._data) - 1
  35.         for i in xrange(n, 0, -1):
  36.             t = self._data[0]
  37.             self._data[0] = self._data[i]
  38.             self._data[i] = t
  39.             self._size -= 1
  40.             self._heapify(0)
  41.  
  42. heap = Heap([1,5,8,9,4,3,2])
  43. print heap._data
  44.  
  45. heap.heapSort()
  46. print heap._data
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement