Reputation: 29
Input array of type integer: [24, 53, 20, 35, 34, 64, 14, 12, 21]
after a recursive function, it should give: [53, 35, 21, 24, 20, 34, 64, 14, 12] the odd numbers places before the even numbers. Experiencing overflow error in the code:
public int[] seperator(int[] arr)
{
int[] newArr = new int[arr.length] ;
int i = 0;
int j = arr.length-1;
int x = 0;
if(i == arr.length-1 && j == 0 && x == arr.length-1)
{
return newArr;
}
else if(arr[x] % 2 != 0)
{
newArr[i] = arr[x];
i++;
}
else
{
newArr[j] = arr[x];
j--;
}
x++;
return seperator(newArr);
}
Upvotes: 0
Views: 84
Reputation: 923
public class Main {
public static void main(String[] arg) {
int[] ar = { 24, 53, 20, 35, 34, 64, 14, 12, 21 };
new Main().swap(ar, 0);
for (int i = 0; i < ar.length; i++) {
System.out.print(ar[i]+" ");
}
}
void swap(int[] ar, int i) {
boolean cont = true; // continue or break checking for odd numbers
if (ar[i] % 2 == 0) {
int j = i;
while (j < ar.length - 1 && ar[j] % 2 == 0) {
j++;
}
int temp = ar[j];
if (j == ar.length - 1) {
cont = false;
}
while (i < j) { // move even numbers forward
ar[j] = ar[j - 1];
j--;
}
ar[i] = temp;
}
if (++i < ar.length && cont)
swap(ar, i); // recursive call
}
}
Upvotes: 0
Reputation: 55
Maybe you can try to use ArrayLists and implement this code:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class oddeven {
public static void main(String[] args) {
List<Integer> l = new ArrayList<Integer>();
Random rd = new Random();
for (int i=0; i<10;i++){
l.add(rd.nextInt(10));
}
List<Integer> lsep = new ArrayList<Integer>(seperator(l));
System.out.println(l);
System.out.println(lsep);
}
public static List<Integer> seperator(List<Integer> l) {
List<Integer> sep = new ArrayList<Integer>();
int i = 0;
int even=0, odd =0;
int len = l.size();
for(i=0; i<len; i++){
if(l.get(i) % 2 == 1) {
odd = l.get(i);
sep.add(odd);
}
}
for(i=0; i<len; i++){
if(l.get(i) % 2 == 0) {
even = l.get(i);
sep.add(even);
}
}
return sep;
}
}
Example,
For a given input :[8, 9, 9, 2, 9, 5, 8, 3, 10, 6]
It will return: [9, 9, 9, 5, 3, 8, 2, 8, 10, 6]
Upvotes: 1