# return value problem

• 01-19-2013, 08:23 PM
laxbro
return value problem
I need to make the mergeSort method return the number of compares and swaps it did but I don't know what I am doing wrong. Still new to java so it's probable simple but I need help. There are some comments from my teacher in their
Code:

public static int[] mergeSort(int[] arr) {

for (int blockSize=1; blockSize<arr.length; blockSize*=2) {

for (int leftIndex=0; leftIndex<arr.length; leftIndex+=2*blockSize) {
// And make this method also return compares and swaps
merge(arr, leftIndex, leftIndex+blockSize, leftIndex+2*blockSize);
}
}
int[] results = new int [3];
results[ARRAY_SIZE]=arr.length;
results[COMPARES]=compares;
results[SWAPS]=swaps;
return results;
}
// Change the return type here, so you can return compares and swaps from it
public static int[] merge(int[] sourceArray, int leftStart, int middleIndex, int rightEnd){
int compares=0, swaps=0;
if (middleIndex>=sourceArray.length) {
// In this case, return 0 compares, and 0 swaps
int[] results = new int [3];
results[COMPARES]=compares;
results[SWAPS]=swaps;
return results;

}
if (rightEnd>=sourceArray.length) {
rightEnd=sourceArray.length;
}
int[] tempArray=new int[sourceArray.length];
for (int i=leftStart; i<rightEnd; i++) {
tempArray[i]=sourceArray[i];
}
int leftIndex=leftStart;
int rightIndex=middleIndex;
int currentCopyIndex=leftStart;
while(leftIndex<middleIndex && rightIndex<rightEnd) {
compares++;
if (tempArray[leftIndex]<tempArray[rightIndex]) {
// Here is a swap
swaps++;
sourceArray[currentCopyIndex]=tempArray[leftIndex];
leftIndex++;
} else {
// Here is another swap
swaps++;
sourceArray[currentCopyIndex]=tempArray[rightIndex];
rightIndex++;
}
currentCopyIndex++;
}
while (leftIndex<middleIndex) {
// This too is a swap
swaps++;
sourceArray[currentCopyIndex]=tempArray[leftIndex];
leftIndex++;
currentCopyIndex++;
}
while (rightIndex<rightEnd) {
// And this is a swap
swaps++;
sourceArray[currentCopyIndex]=tempArray[rightIndex];
rightIndex++;
currentCopyIndex++;
}
int[] results = new int [3];
results[COMPARES]=compares;
results[SWAPS]=swaps;
return results;
}

• 01-19-2013, 09:39 PM
Re: return value problem
one thing that will make it a LOT easier is if you break your swap and compare statements out into separate methods. That way, you can increment your counter every time the method is called!
• 01-21-2013, 08:38 PM
laxbro
Re: return value problem
It has to be done this way for the test program to work
• 01-22-2013, 10:46 AM
Tolls
Re: return value problem
No it doesn't.
Your test program will simply be calling the merge method (presumably).
Whether that merge method then calls other methods should be irrelevant to it.

Unless you have been given a very silly test program.