python - Is This a Valid HeapSort? -
for past 6 hours, i've been reading tutorials , academic material on constructing heapsort. have prototyped in python sorts list of integers. however, i'm not entirely sure whether or not solution constitutes valid heapsort. it's simplistic solution , can improved upon, i'm wondering whether valid @ all. confusingly, seems have own 'preferred' way of implementing algorithm.
many in advance.
def heapsort(array): array = heapify(array) array = insert(array, 9999) print(array) def heapify(array): end = len(array) = 0 j = 0 while < end: while j < end: if array[i] > array[j]: array = swap(array, i, j) j += 1 += 1 j = return array def insert(array, x): array.append(x) return heapify(array) def swap(array, a, b): temp = array[a] array[a] = array[b] array[b] = temp return array def main(array): heapsort(array) if __name__ == '__main__': array = [3, 1, 2, 4, 6, 7, 9, 0] main(array)
your heapify() should comparing elements of parent/child within heap (tree structure). relative location within array
childindex = 2 * parent index + [0|1] # 2 children per parent
in terms of index array. not evident in implementation.
Comments
Post a Comment