Nathan Sprague
10/30/17
private static void mergesort(int[] items, int[] temp,
int left, int right) {
if (left == right) {
return;
}
int mid = (left + right) / 2;
mergesort(items, temp, left, mid);
mergesort(items, temp, mid + 1, right);
merge(items, temp, left, mid, right);
}
Socrative... Given that merge
requires f(n) comparisons to merge n elements, provide a recurrence relation describing the worst-case number of comparisons performed by mergesort.
private static void merge(int[] items, int[] temp,
int left, int mid, int right) {
for (int i = left; i <= right; i++) {
temp[i] = items[i];// Copy subarray to temp
}
int i1 = left;
int i2 = mid + 1;
for (int curr = left; curr <= right; curr++) {
if (i1 == mid + 1) { // Left subarray exhausted
items[curr] = temp[i2++];
} else if (i2 > right) { // Right subarray exhausted
items[curr] = temp[i1++];
} else if (temp[i1] <= temp[i2]) { // Get smaller value (COUNT THIS!)
items[curr] = temp[i1++];
} else {
items[curr] = temp[i2++];
}
}
}
Socrative... How many comparisons (between keys) are performed by merge
in the worst case?
W(1)=0
W(n)=n−1+2W(n2)
Now we can write down the overall sum: i∑j=0n−2j
i is determined by the initial condition...
n/2i=1
i=log2n
Substituting: ∑log2nj=0n−2j
Useful fact: ∑nj=02j=2n+1−1
log2n∑j=0n−2j =log2n∑j=0n−log2n∑j=02j =n(log2n+1)−log2n∑j=02j (Apply useful fact.) =n(log2n+1)−(2log2n+1−1) =nlog2n+n−(2n−1) =nlog2n−n+1
Repeat the analysis for assignments...