Debugging Heapsort in Python
Question: I know how to program in Java, I am very new to python. I am trying to
implement HeapSort in Python but I am unable to get where this code went
wrong. Can anyone help ?

This is my implementation:

    
    
    class HeapSort:
    
        def sort(self,list):
            self.p = list
            self.N = len(list)
            for k in range(N/2,1,-1):
                sink(k,N)
    
            while N> 1:
                exch(1,N)
                N -=1
                sink(1,N)
    
    # Helper Functions to restore the heap invariant
    
        def sink(k,N):
            while 2*k <= N:
                j = 2*k
                if (j<N & (j < j+1)):
                    j += 1
                if (j < k):
                    break
                exch(k,j)
                k = j
    
        def exch(i,j):
            p[i],p[j] = p[j],p[i]
    
    # Helper Functions to debug
    
        def isSorted(list):
            for k in range(1,len(list)):
                return False
            return True
    
    
        L = [6, 4, 2, 8, 1, 9, 3, 0, 12, 5]
        print(L)
        h = HeapSort()
        h.sort(L)
        print(L)     
    

The output I am getting is

    
    
    [6, 4, 2, 8, 1, 9, 3, 0, 12, 5]
        NameError: "name 'HeapSort' is not defined"
    
        module body in heapsort.py at line 26
        class HeapSort:
        function HeapSort in heapsort.py at line 64
        h = HeapSort()
    


Answer: IF your indentation is accurate, it is causing you to try to call HeapSort in
your definition of HeapSort.

Instead you would want

    
    
    class HeapSort():
        ...
    
    def main():
        L = [6, 4, 2, 8, 1, 9, 3, 0, 12, 5]
        print(L)
        h = HeapSort()
        h.sort(L)
        print(L)
    
    if __name__ == '__main__':
        main()
    

This allows you to run the file in which you define your class, and if other
files import the class, it will not run the code.

**EDIT**

The above will fix the error that you are getting, but if you see @Matt's
comments, but you are running tests _within_ your `heapsort.py` file, you
should move these to an external `heapsort-tests.py` file and import your
class with

    
    
    from heapsort import HeapSort
    

**EDIT 2**

If you are treating this as a class you want to use and pass around as an
instantiated object, then you need to pass `self` to all of your methods and
call them with `self.method_name()`, i.e. `self.sink(x,y)`. If not, you would
sort by calling something like `HeapSort.sort(L)` instead of creating `h`.

