1. Shown below is the code for the insertion sort consisting of
two recursive methods that
replace the two nested loops that would be used in its iterative
counterpart:
void insertionSort(int array[])
{
insert(array, 1);
}
void insert(int[] array, int i)
{
if (i < array.length)
{
int value = array[i];
int j = shift(array, value, i);
array[j] = value;
insert(array, i + 1);
}
}
int shift(int[] array, int value, int i)
{
int insert = i;
if (i > 0 && array[i - 1] > value)
{
array[i] = array[i - 1];
insert = shift(array, value, i - 1);
}
return insert;
}
Draw the recursion tree for insertionSort when it is called for an
array of length 5 with
data that represents the worst case. Show the activations of
insertionSort, insert and
shift in the tree. Explain how the recursion tree would be
different in the best case.
2. Refer back to the recursion tree you provided in the
previous problem. Determine a
formula that counts the numbers of nodes in that tree. What is
Big- for execution time?
Determine a formula that expresses the height of the tree. What is
the Big- for memory?
**I only need help on number 2.**
2)
Formula for that counts the number of nodes in recursion tree: C(n)
= n*(n-1)/2 //n is number of elements //derived from C(n) =
C(n-1)+n
execution time : T(n) = n*(n-1)/2 = O(n^2)
formula for height: 2 //it constant, the max height possible is 2
only //because we consider recursive calls as parallel nodes
bigO for memory:
since we are using recursion, it needs stack space so: O(n^2) //for
each recursive call
if we are not considering stack space then
space is :O(1)
Get Answers For Free
Most questions answered within 1 hours.