1

I have written the following heap sort code and I get the wrong output (not sorted) at times and I can't seem to find why...any help will be much appreciated! (WARNING: I am still learning Python that might be the problem)

def heap_sort(self, a):

    self.build_max_heap(a)
    n = len(a)-1
    i = len(a)-1

    for i in range(len(a)-1, 1):
        temp = a[0]
        a[0] = a[i]
        a[i] = temp
        a.heapsize = heapsize - 1
        self.max_heapify(a, 0)       #rebuild max heap at with new root



def max_heapify(self, a, i):

    left = (2*(i+1))-1      #left child of i
    right = 2*(i+1)             #right child of i
    largest = i

    if left < a.heapsize and a[left] > a[i]:
        largest = left

    if right < a.heapsize and a[right] > a[largest]:
        largest = right

    if largest != i:
        temp = a[largest]
        a[largest] = a[i]
        a[i] = temp
        self.max_heapify(a, largest)



def build_max_heap(self, a):

    heapsize = len(a)
    i = int(heapsize/2)-1

    for i in range(i, 0):
        self.max_heapify(a, i)

These are my tests:

#--Test for 0 in array--#
def zero_array(self):
    a = [12,0,232]
    print self.sort.heap_sort(a)
    return

#--Test for duplicate in array--#
def duplicate_array(self):
    a = [12, 12, 7]
    print self.sort.heap_sort(a)
    return

#--Test for all same values in array--#
def allsame_array(self):
    a = [1,1,1]
    print self.sort.heap_sort(a)
    return

#--Test for negative values in array--#
def negative_array(self):
    a = [-23, -2, 123]
    print self.sort.heap_sort(a)
    return

I get the following returned arrays (which are suppose to be sorted):

    [12, 0, 232]
    [12, 12, 7]
    [1, 1, 1]
    [-23, -2, 123]
1
  • Two side points: first, your n = and i = lines in heap_sort don't do anything -- you never use n and you immediately clobber i in the loop. Second, you can swap two entries in a list using something like a[0], a[i] = a[i], a[0] without needing a temp. Commented Oct 15, 2012 at 16:00

1 Answer 1

1

I see one issue right away:

for i in range(len(a)-1, 1)

If you want to go down to 1 inclusive use:

for i in range(len(a)-1, 0, -1)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that fixed it! ... And for that I now love you... (knew it was some python syntax issue lol)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.