Overview
remove.)What’s the best way to create the temporary array for mergesort?
Option one
T[] temp = (T[]) new Object[size];
Option two
T[] temp = arr.clone(); // Gives a new array, with same values
What events should we logged during merge?
You will be comparing elements in the two halves of the array. You should log those as comparison events.
You will copy elements back from the scratch array to the main array. You should log those as copy events.
E.g., [1,5,8,2,3,4]: compare(0,3),compare(1,3),compare(1,4),compare(1,5), copy(1,0), copy(2,1), copy(3,2), copy(4,3), copy(5,4), copy(8,5).
You should only log the primary changes to the original array, since those are the only ones we will “visualize”.
Note: I thought about using the Anya/PM version of the lab, but decided against it, so I wrote a brand-new lab.
If you are assigned the iterative version, here’s pseudocode
if (root is null)
set the root to a new node
else
set current to root
while (...)
compare key to current.key
case =:
replace the value
return the old value
case <:
if there is a left subtree,
current = left
otherwise
current.left = new node
add 1 to size
return null
case >:
if there is a right subtree,
current = right
otherwise
current.right = new node
add 1 to size
return null
If you are assigned the recursive version, here’s pseudocode.
function set(key, value)
root = setHelper(root, key, value)
return cache
function setHelper(node, key, value)
if node == null
set cache to null
add 1 to size
return a new node
else
compare key to node.key
case =:
set cache to value in node
update value in node
return node
case <:
node.left = setHelper(node.left, key, value);
return node;
else
node.right = setHelper(node.right, key, value);
return node;