Java recursion, can’t get the output?

Question:

Hi,
I’m trying to write this recursive java program for practice, Merge Sort to be exact. Can anyone help me with what might be going wrong here? Thanks so much.

-Kyle
Code Snippet:

//write merge sort

int[] mergeSub(int[] array, int left, int right){
int mid = (left+right)/2;
int[] left = new merge(array, left, mid);
int [] right = new merge(array, mid+1, right);
return merge(left, right);
}
int[] merge(int[] left, int[] right){
int index =0; int indexLeft =0; int indexRight=0;
int[] result = new int[left.length+right.length];

while(indexLeft<left.length && indexRight<right.length){
if(left[indexLeft] <= right[indexRight])
{
result[index]=left[indexLeft];
index++;
indexLeft++;
}
else{
result[index]=right[indexRight];
index++;
indexRight++;
}
}
if (indexLeft<left.length){
while(indexLeft<left.length){
result[index]=left[indexLeft];
indexLeft++; index++;
}
}
if (indexRight<right.length){
while(indexRight<left[indexRight]){
result[index]=right[indexRight];
indexRight++; right[indexRight]++;
}
}
return result;
}
public static void main(String args[]){

int[] array = {2, 4, 5, 7, 5, 6, 3, 5, 7, 8};
System.out.println(mergeSub(array, 0, 9));
}

Solution:

In the code below, the only valid value of “left” is zero. you have created an array of length 1, Since it is an array of ints, the members of the array are set to value 0 at the time of creation.

This pair of lines is a no-op when left == 0 , and ArrayIndexOutOfBounds exception when left != 0
int[] arr = new int[1];
arr[0] = arr[left];

Tags: · ·
digg delicious stumbleupon technorati Google live facebook Sphinn Mixx newsvine reddit yahoomyweb
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...