I have two heapsort algorithms. The first one was written by me, and the second one from some website. For me, both have the same logic, but the second does better than the first. Why is this happening? The only difference that I see is that mine uses recursion and the other is iterative. Could this be a differentiating factor?
My code is:
def heapify(arr,i,n): pivot = arr[i]
Another code:
def HeapSort(A): def heapify(A): start = (len(A) - 2) / 2 while start >= 0: siftDown(A, start, len(A) - 1) start -= 1 def siftDown(A, start, end): root = start while root * 2 + 1 <= end: child = root * 2 + 1 if child + 1 <= end and A[child] < A[child + 1]: child += 1 if child <= end and A[root] < A[child]: A[root], A[child] = A[child], A[root] root = child else: return heapify(A) end = len(A) - 1 while end > 0: A[end], A[0] = A[0], A[end] siftDown(A, 0, end - 1) end -= 1
Even for a small array about 100,000 in size, the difference becomes significant. I call any code simply by passing an array to sort into a function: HeapSort(list) or HeapSort(list) .
Edit:
I replaced the heapsort function with this:
def heapsort(array): n = len(array) heapit(array,n) array[n-1],array[0] = array[0],array[n-1] for i in range(n-1): heapify(array,0,n-1-i) array[ni-2],array[0] = array[0],array[ni-2]
This gives comparable performance, but still slower. For an array of $ 1 million, the result is almost 20 seconds: 4 seconds. What else can be done?