递归地将数字分开,取决于它是奇数还是偶数

时间:2014-02-10 00:23:44

标签: java

整数类型的输入数组:[24,53,20,35,34,64,14,12,21]

在递归函数之后,它应该给出:[53,35,21,24,20,34,64,14,12] 奇数位于偶数之前。 在代码中遇到溢出错误:

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);
}

2 个答案:

答案 0 :(得分:1)

也许您可以尝试使用ArrayLists并实现此代码:

   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;
   }
}

实施例,

对于给定的输入:[8,9,9,2,9,5,8,3,10,6]

它将返回:[9,9,9,5,3,8,2,8,10,6]

答案 1 :(得分:0)

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
  }
}