-
Notifications
You must be signed in to change notification settings - Fork 953
Open
Description
| private static void exch(Object[] pq, int i, int j) { |
Thanks for your work on this. I'm currently going over the book and I have been a little off by the section on Heapsort. One of the things that I was confused about was dealing with the index 1 to N in the sorting method. I noticed from your implementation that you use -1 in the swap and in the less but have you tested?
class Heap
# Trickledown
def sink(a, k, n)
while 2 * k <= n
j = 2 * k # child
if !a[j + 1].nil? # check if there is a right child
j += 1 if j > 1 && less(a, j, j + 1) # if left child less than right child
end
break if !less(a, k, j) # If parent greater than child break
swap(a, k, j)
k = j
end
end
def sort(a)
n = a.length
k = n / 2
while k >= 1
sink(a, k, n)
k -= 1
end
while n > 1
swap(a, 1, n)
n -= 1
sink(a, 1, n)
end
a
end
def less(pq, i, j)
pq[i - 1] < pq[j - 1]
end
def swap(a, i, j)
temp = a[i - 1]
a[i - 1] = a[j - 1]
a[j - 1] = temp
end
end
When I do your implementation in Ruby I get the error for as the answer ["A", "M", "E", "L", "E", "O", "P", "R", "S", "T", "X"] and I haven't been able to figure out why.
I created the following post on Stackoverflow
https://stackoverflow.com/questions/63634906/ruby-heapsort-sink-undefined-method-for-nilnilclass
trying to figure out where am I off.
Metadata
Metadata
Assignees
Labels
No labels