I am getting a stack overflow error in my merge sort. Not sure why yet.
//BAD CODE BAD CODE
public static void main(String[] args) {
int[] S = {3,4,6,2,5,3,7};
mergesort(S, 1, 5);
System.out.println(S);
}
public static void mergesort(int[] S, int left, int right){
if (right <= 1) { return; }
int mid = (right + left) / 2;
mergesort (S, left, mid);
mergesort (S, mid+1, right);
merge(S, left, mid, right);
}
public static void merge(int[] S, int left, int mid, int right){
int i, j;
int[] aux = new int[S.length];
for (i = mid+1; i > left; i--) {aux[i-1] = S[i-1];}
for (j = mid; j < right; j++) {aux[right+mid-j] = S[j+1];}
for (int k = left; k <= right; k++){
if (aux[j] < aux[i]) {
S[k] = aux[j--];
} else{
S[k] = aux[i++];
}
}
}
//END OF BAD CODE
Update
Thank you for all of the quick responses, I got it working and made some suggested changes. Copy and paste, try it out:
//GOOD CODE
package longest_sequence_proj;
import java.util.*;
public class MergeTest {
/**
* @param args
*/
public static void main(String[] args) {
int[] S = {3,4,6,2,5,3,7};
mergesort(S, 0, 6);
System.out.println(Arrays.toString(S));
}
public static void mergesort(int[] S, int left, int right){
if (right <= left) { return; }
int mid = (right + left) / 2;
mergesort (S, left, mid);
mergesort (S, mid+1, right);
merge(S, left, mid, right);
}
public static void merge(int[] S, int left, int mid, int right){
int i, j;
int[] aux = new int[S.length];
for (i = mid+1; i > left; i--) {aux[i-1] = S[i-1];}
for (j = mid; j < right; j++) {aux[right+mid-j] = S[j+1];}
for (int k = left; k <= right; k++){
if (aux[j] < aux[i]) {
S[k] = aux[j--];
} else{
S[k] = aux[i++];
}
}
}
}
Your stop clause is wrong:
You actually want to stop when the size of the partial array used is smaller then one, so you are probably looking for:
As a side note:
I guess it is not what you want (It does not print the array, rather the identifier of the object…)
In order to print the array use: