- #1
courtrigrad
- 1,236
- 2
Hello all
Let's say we have the following classes:
and
How would I print the array? I am stuck. I wrote the two classes but don't know how to get the output. Do I need a for loop?
Thanks
Let's say we have the following classes:
Code:
public class Merge {
protected static void merge(int[] a, int first, int last, int middle) {
int i, j, k;
int[] tempArray = new int[a.length];
i = first;
j = first;
k = middle + 1;
while(j <= middle && k <= last){
if(a[j] <= a[k])
tempArray[i++] = a[j++];
else
tempArray[i++] = a[k++];
}
while(j <= middle)
tempArray[i++] = a[j++];
while(k <= last)
tempArray[i++] = a[k++];
for (i = first; i <= last; i++)
a[i] = tempArray[i];
}
}
and
Code:
public class MergeSort extends Merge {
public static void mergeSort(int[] a, int first, int last) {
if(last==first) return;
if (last - first == 1) {
// not a[0]>a[1]; this part could test on the upper half of the array
if (a[first] > a[last]) {
int temp = a[first];
a[first] = a[last];
a[last] = temp;
}
} else {
int halfwayPoint = (int) (last + first) / 2;
mergeSort(a, first, halfwayPoint);
mergeSort(a, halfwayPoint + 1, last);
merge(a, first, last, halfwayPoint);
}
}
}
How would I print the array? I am stuck. I wrote the two classes but don't know how to get the output. Do I need a for loop?
Thanks