Reference no: EM131924818
Assignment
1. Shown below is the code for the insertion sort consisting of two recursive methodsthat replace the two nested loops that would be used in its iterativecounterpart:
void insertionSort(int array[])
{
insert(array, 1);
}
void insert(int[] array, inti)
{
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, inti)
{
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 insertionSortwhen it is called for an array of length 5 with data that represents the worst case. Show the activations of insertionSort, insert and shiftin 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-Θ formemory?
3. Provide a generic Java class named SortedPriorityQueuethat implements a priority queue using a sorted list implemented with the Java ArrayListclass. Make the implementation as efficient aspossible.
4. Consider the following sorting algorithm that uses the class you wrote in theprevious problem:
void sort(int[] array)
{
SortedPriorityQueue<Integer> queue = new SortedPriorityQueue(); for (inti = 0; i<array.length; i++)
queue.add(array[i]);
for (inti = 0; i<array.length; i++) array[i] = queue.remove();
}
Analyze its execution time efficiency in the worst case. In your analysis you may ignore the possibility that the array list may overflow and need to be copied to a larger array.
Indicate whether this implementation is more or less efficient than the one that uses the Java priority queue.