Created
June 16, 2017 07:06
-
-
Save ritwikd/e23deecb35e5f5181d46cdbf394f4921 to your computer and use it in GitHub Desktop.
Heapsort in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'''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