I'm using a method to sort out an array with even numbers coming out in the front and odd numbers in the back of the array. My assignment dictates that i accomplish this using recursion. When I try to print the sorted out array it just prints out the array unsorted. What am i doing wrong?
The left variable starts at index 0 and the right variable starts at the end of the index. They are then both compared, if left is an odd number and right is an even number then they swap values. If left turns out to be an even number then no swap takes place and it points at the next index in the array. If right turns out to be an odd number then no swap takes place and it points at the next index in the array. It does this until all the even numbers are on the right of the array.
I'm getting a
"Exception in thread "main" java.lang.StackOverflowError".
import java.util.*;
public class Problem2{
//i=left
//j=right
//first i tried to shift the whole thing
//have all even numbers pop to the front of array when even
public static int[] callme(int[] arry, int left, int right){
int temp;
if(left>=right) //base case, return array
return arry;
else if(arry[left]%2!=0 && arry[right]%2==0){//if match, do the swap
temp=arry[left];
arry[left]=arry[right];
arry[right]=temp;
return callme(arry, left++, right--);
}
else{
if(arry[right]%2!=0){//if right side is on odd #, then decrease index
return callme(arry, left, right--);
}
if(arry[left]%2==0){//if left side is on even #, then increase index
return callme(arry, left++, right);
}
}
return arry;
}
public static void main(String[] args){
//int index=0;
int[] arry={3,5,6,8};
int[] newarry=callme(arry, 0, arry.length-1);
System.out.print("The new sorted array is: ");
for(int i=0; i<newarry.length;i++){
System.out.print(newarry[i]+" ");
}
}
}