views:

47

answers:

2

Link

public Node merge(Node x, Node y) {
  if(x == null)
    return y;
  if(y == null) 
    return x;

  // if this was a max height biased leftist tree, then the 
  // next line would be: if(x.element < y.element)
  if(x.element.compareTo(y.element) > 0) {  
    // x.element > y.element
    Node temp = x;
    x = y;
    y = temp;
  }

  x.rightChild = merge(x.rightChild, y);

  if(x.leftChild == null) {
    // left child doesn't exist, so move right child to the left side
    x.leftChild = x.rightChild;
    x.rightChild = null;
    x.s = 1;
  } else {
    // left child does exist, so compare s-values
    if(x.leftChild.s < x.rightChild.s) {
      Node temp = x.leftChild;
      x.leftChild = x.rightChild;
      x.rightChild = temp;
    }
    // since we know the right child has the lower s-value, we can just
    // add one to its s-value
    x.s = x.rightChild.s + 1;
  }
  return x;
}

What makes me ask this question is:

  if(x.element.compareTo(y.element) > 0) {  
    // x.element > y.element
    Node temp = x;
    x = y;
    y = temp;
  }

Isn't that just not gonna work, since the references are only switched inside the method?

A: 

Isn't that just not gonna work, since the references are only switched inside the method?

The rest of the method will operate on the switched references, making the switch quite meaningful.

Michael Borgwardt
+1  A: 

It is switching them for the purposes of the later executions inside the method. Although the switch does not change any references directly outside the method, the check is done so that there is only one path of logic through the code, with the smaller valued element always being in the x node, so that their swapping later in the code works with the correct elements.

For one specific example, look at the next line of code:

x.rightChild = merge(x.rightChild, y);

Whichever is the smaller of the two (x or y) will be merging underneath it, at it's right child, the larger of the two. So, this allows the method itself to worry about the ordering, and means that the two elements can be added in any order, and the correct behavior will occur because of it.

Hope this helps.

aperkins