Ok, so I am trying to implement a merge sort in java, but i am running into the following error in the splitting of the array:
Exception in thread "main" java.lang.IllegalArgumentException: 2 > 1
at java.util.Arrays.copyOfRange(Arrays.java:3591)
at MergeSortS.recMergeSort(MergeSortS.java:26)
at MergeSortS.recMergeSort(MergeSortS.java:28)
at MergeSortS.mergeSort(MergeSortS.java:17)
at MergeSortM.main(MergeSortM.java:16)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
My code segment is as follows, please help me identify my issue here...:(
I have purposely commented out recMergeSort(right)
recursive call at the end because I want to correct the recMergeSort(left)
call...
public void recMergeSort(int[] tempArray){
if(tempArray.length>1){
int mid=(tempArray.length)/2;
int[] left=Arrays.copyOfRange(tempArray,0,mid);
int[] right=Arrays.copyOfRange(tempArray,mid+1,tempArray.length-1);
recMergeSort(left);
//recMergeSort(array, right, mid+1, right.length-1);
}
}
EDIT
Ok, so I checked another site and the javadoc on copyOfRange
method requiring the following:
Parameters:
original - the array from which a range is to be copied
from - the initial index of the range to be copied, **inclusive**
to - the final index of the range to be copied, **exclusive**. (This index may lie outside the array.)
After fixing this as follows:
public void recMergeSort(int[] tempArray){
if(tempArray.length>1){
int mid=(tempArray.length)/2;
int[] left=Arrays.copyOfRange(tempArray,0,mid+1);
int[] right=Arrays.copyOfRange(tempArray,mid+1,tempArray.length);
recMergeSort(left);
//recMergeSort(array, right, mid+1, right.length-1);
}
}
I get the following error:
Exception in thread "main" java.lang.StackOverflowError
Please help me correct this issue...:(
After factoring in all the errors you pointed out, I got it to working by changing the following along with the edits on the OP:
Thank you all for your support. I wasted one whole day trying to figure out this mess!