Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementation of Heap sort #15

Open
theasteve opened this issue Aug 28, 2020 · 0 comments
Open

Implementation of Heap sort #15

theasteve opened this issue Aug 28, 2020 · 0 comments

Comments

@theasteve
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant