1. Member Join Date
Jan 2013
Posts
7
Rep Power
0

## 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
Java 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 ;
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 ;
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 ;
results[COMPARES]=compares;
results[SWAPS]=swaps;
return results;
}```
Last edited by laxbro; 01-19-2013 at 08:26 PM.  Reply With Quote

2. ## 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!  Reply With Quote

3. Member Join Date
Jan 2013
Posts
7
Rep Power
0

## Re: return value problem

It has to be done this way for the test program to work  Reply With Quote

4. Moderator   Join Date
Apr 2009
Posts
13,541
Rep Power
27

## 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.  Reply With Quote

compares, merge sort algorithm, return value 