Help! I have merge and mergeSort here but on my assignment im not able to import
ID: 3908518 • Letter: H
Question
Help! I have merge and mergeSort here but on my assignment im not able to import the array class. How can i replace it using a for loop?
public static <K> void mergeSort(K[] S, Comparator<K> comp) {
int n = S.length;
if (n < 2) {
return; // array is trivially sorted
}
// divide
int mid = n / 2;
K[] S1 = Arrays.copyOfRange(S, 0, mid); // copy of ?rst half
K[] S2 = Arrays.copyOfRange(S, mid, n); // copy of second half
// conquer (with recursion)
mergeSort(S1, comp); // sort copy of ?rst half
mergeSort(S2, comp); // sort copy of second half
// merge results
merge(S1, S2, S, comp); // merge sorted halves back into original
}
public static <K> void merge(K[] S1, K[] S2, K[] S, Comparator<K> comp) {
int i = 0, j = 0;
while (i + j < S.length) {
if (j == S2.length || (i < S1.length && comp.compare(S1[i], S2[j]) < 0)) {
S[i + j] = S1[i++];// copy ith element of S1 and increment i
} else {
S[i + j] = S2[j++]; // copy jth element of S2 and increment j
}
}
}
Explanation / Answer
in input arguments use list datastructure to pass as argument.
Copy list values in temporary array and perform mergesort
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.