Beruflich Dokumente
Kultur Dokumente
class MergeSortTest {
/*
* Objects containing an array of integers together
* with methods for carrying out a merge-sort.
*/
class MergeSort {
/*
* Initialise the data array with some test data.
* Return the updated MergeSort object.
* DO NOT CHANGE THIS METHOD
*/
/*
* Sort the data array into ascending order.
* Return the updated MergeSort object.
* DO NOT CHANGE THIS METHOD
*/
public MergeSort sort() {
data = this.mergeSort(data);
return this;
}
/*
* Print the contents of the data array from left to right.
* Return the length of the data array.
*/
public int printData() {
// TO BE COMPLETED
for (int i : data) {
System.out.println(i);
}
return data.length;
}
/*
* Create and return a new array containing an in-order merge of the values
* from a1 and a2.
* This method should assume that a1 and a2 have already been sorted
* into ascending order.
*/
public int[] merge(int[] a1, int[] a2) {
// TO BE COMPLETED
int length = a1.length + a2.length;
int[] sort = new int[length];
int indexa1 = 0, indexa2 = 0, indexRes = 0;
/*
* Create and return an array which contains the same data as arr
* but sorted into ascending order.
* It is permitted, but not required, for this method to simply return
* arr if arr is already sorted in ascending order.
*/
public int[] mergeSort(int[] arr) {
// TO BE COMPLETED MAKING USE OF THE merge METHOD
// The basic idea of merge-sort is to split the array
// into two roughly equal parts, recursively call mergeSort
// to sort the two halves, then merge the sorted halves to
// produce the final result);
if (arr.length <= 1) {
return arr;
}
int mid = arr.length / 2;
int[] a1 = new int[mid];
int[] a2;
if (arr.length % 2 == 0) {
a2 = new int[mid];
} else {
a2 = new int[mid + 1];
}
return sorted;
}
}