Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Thinking recursively :(

Name: Anonymous 2011-12-12 20:55

I need some help thinking recursively. I've never had to use this board before, but it's finals week and I'm desperate to get this project done so I can start studying. I had to modify several parts of a java heap program, but one part that's stumping me is converting one function with a while loop into a recursive function. Here's the code:

<code>
   public void trickleUp(int index)
   {
      int parent = (index-1) / 2;
      Node bottom = heapArray[index];

      while( index > 0 && heapArray[parent].getKey() > bottom.getKey() )
         {
         heapArray[index] = heapArray[parent];  // move it down
         index = parent;
         parent = (parent-1) / 2;
         }  // end while
      heapArray[index] = bottom;
   }  // end trickleUp()
</code>

How the hell do I convert this into a recursive function with a void function? My professor said the interface of the method should remain the same.

Name: Anonymous 2011-12-13 9:32

I normally wouldn't do this, but it's finals week here too and I'm feeling generous. Here you go, anon. Good luck with your finals.

public void trickleUp(int index)
{
   int parent = (index-1) / 2;
   Node bottom = heapArray[index];
   Node top = heapArray[parent];

   // This only works for a maxheap. Use < for a minheap
   if (index > 0 && top.getKey() > bottom.getKey())
   {
      swap(index, parent);
      trickleUp(parent);
   }
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List