値の配列をマージソートするメソッドを作成しました。方法は完璧に機能しますが、私は行われた比較と交換の数を表示しようとしています。私の最初の考えは、静的変数(int比較、int交換)を作成し、それらをメソッドに渡すことでした。ただし、ヘルパーメソッドからそれらを返す際に問題が発生しています。同じメソッドでint[]と2つのintを返すことは可能ですか?そうでない場合、行われた比較と交換の数をどのように判断できますか?
これが私のmergeSortメソッドとmergeメソッドです。
public static int[] mergeSort(int[] A, int comps, int exchs) {
// Array has only 1 element
if( A.length <= 1 ) {
return A;
}
int midPoint = A.length / 2;
// Initialize left and right arrays.
int[] left = new int[midPoint];
int[] right = new int[A.length - midPoint];
System.arraycopy(A, 0, left, 0, midPoint);
System.arraycopy(A, midPoint, right, 0, A.length - midPoint);
//recursively sort left and right arrays
left = mergeSort(left, comps, exchs);
right = mergeSort(right, comps, exchs);
System.out.println("Comparisons" + comps);
System.out.println("Exchanges" + exchs);
return merge(left, right, comps, exchs);
}
private static int[] merge(int[] left, int[] right, int comps, int exchs){
// Initialize the result array.
int[] res = new int[left.length + right.length];
// Initialize the array indexes.
int leftIndex = 0;
int rightIndex = 0;
int resIndex = 0;
// compare each element and merge results
while(leftIndex < left.length && rightIndex < right.length){
if(left[leftIndex] > right[rightIndex]){
res[resIndex] = right[rightIndex];
exchs++;
rightIndex++;
} else {
res[resIndex] = left[leftIndex];
exchs++;
leftIndex++;
}
comps++;
resIndex++;
}
comps++;
// Append remainder of left array into the result array.
while(leftIndex < left.length){
res[resIndex] = left[leftIndex];
exchs++;
leftIndex++;
resIndex++;
}
comps++;
// Append whatever is left from the right array into the result array.
while(rightIndex < right.length) {
res[resIndex] = right[rightIndex];
exchs++;
rightIndex++;
resIndex++;
}
comps++;
return res; // want to return comparisons and exchanges to mergeSort method
}