Skip to content

Instantly share code, notes, and snippets.

@ritwikd
Created June 16, 2017 07:06
Show Gist options
  • Save ritwikd/e23deecb35e5f5181d46cdbf394f4921 to your computer and use it in GitHub Desktop.
Save ritwikd/e23deecb35e5f5181d46cdbf394f4921 to your computer and use it in GitHub Desktop.
Heapsort in Python
'''Heapsort by Ritwik Dutta'''
class Heap(object):
'''Heap Class'''
def __init__(self, nums=None):
self.nums = nums
def heapify(self, n_index):
''' Heapify at given node'''
size = len(self.nums)
lc_index, rc_index = n_index * 2 + 1, n_index * 2 + 2
lc_exists, rc_exists = lc_index < size, rc_index < size
if lc_exists and rc_exists:
tc_index = lc_index if self.nums[lc_index] > self.nums[rc_index] else rc_index
elif lc_exists and not rc_exists:
tc_index = lc_index
elif rc_exists and not lc_exists:
tc_index = rc_index
else: return
if self.nums[tc_index] > self.nums[n_index]:
self.nums[tc_index], self.nums[n_index] = self.nums[n_index], self.nums[tc_index]
def sort(self):
'''Sort given nums'''
sort = []
while self.nums:
l_tn = int(len(self.nums) / 2) - 1
map(self.heapify, list(xrange(l_tn, -1, -1)))
sort.insert(0, self.nums[0])
self.nums = self.nums[-1::-1][:-1]
return sort
HEAPSORT = lambda nums: Heap(nums).sort()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment