在数组中交换奇数和偶数 [英] Swap odd and even numbers in array

查看:157
本文介绍了在数组中交换奇数和偶数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个网站上看到了这段代码。它使用一种方法来排序一个数组,其中偶数出现在前面,而奇数出现在数组的后面。我想知道你是否可以做同样的事情,除了先让奇数出现然后出现偶数?我试过但无济于事。我是java的新编码,我想测试递归。

I saw this code on this site. It uses a method to sort out an array with even numbers coming out in the front and odd numbers in the back of the array. I was wondering if you could do the same thing except make the odd numbers appear first and then the even numbers afterward? I tried but to no avail. I am new to coding in java and I wanted to test recursion.

public class Recurse {

//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[] seperator(int[] arr1, int left, int right){
    int temp;
    if(left>=right)       //base case, return array
        return arr1; 
    else if(arr1[left]%2!=0 && arr1[right]%2==0){//if match, do the swap
        temp=arr1[left];
        arr1[left]=arr1[right];
        arr1[right]=temp;   
        return seperator(arr1, left+1, right-1);
    }
    else{
        if(arr1[right]%2!=0){//if right side is on odd #, then decrease index
            return seperator(arr1, left, right-1);
        }
        if(arr1[left]%2==0){//if left side is on even #, then increase index
            return seperator(arr1, left+1, right);
        }
    } 
    return arr1;
}

public static void main(String[] args){

    //int index=0;
    int[] arry={70,13,48,19,24,5,7,10};

    int[] newarry=seperator(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]+" ");
    } 
}

}

输出是这样的:

  The new sorted array is: 70 10 48 24 19 5 7 13


推荐答案

好吧,如果你想先得到奇数,请更换任何%2!= 0 %2 == 0 ,任何%2 == 0 %2!= 0

Well, if you want the odd numbers to come first, replace any %2!=0 with %2==0 and any %2==0 with %2!=0 :

  public static int[] seperator(int[] arr1, int left, int right){
    int temp;
    if(left>=right)       
      return arr1; 
    else if(arr1[left]%2==0 && arr1[right]%2!=0){
      temp=arr1[left];
      arr1[left]=arr1[right];
      arr1[right]=temp;   
      return seperator(arr1, left+1, right-1);
    }
    else{
      if(arr1[right]%2==0){//if right side is on even #, then decrease index
        return seperator(arr1, left, right-1);
      }
      if(arr1[left]%2!=0){//if left side is on odd #, then increase index
        return seperator(arr1, left+1, right);
      }
    } 
    return arr1;
  }

这篇关于在数组中交换奇数和偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆