Java 数组偶数和奇数排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3930884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:06:21  来源:igfitidea点击:

Array even & odd sorting

java

提问by Sumithra

I have an array where i have some numbers. Now i want to sort even numbers in a separate array and odd numbers in a separate. Is there any API to do that. I tried like this

我有一个数组,其中有一些数字。现在我想在单独的数组中对偶数进行排序,在单独的数组中对奇数进行排序。是否有任何 API 可以做到这一点。我试过这样

int[] array_sort={5,12,3,21,8,7,19,102,201};
int [] even_sort;
int i;
for(i=0;i<8;i++)
{

if(array_sort[i]%2==0)
{
     even_sort=Arrays.sort(array_sort[i]);//error in sort

System.out.println(even_sort);
}
}

采纳答案by BjornS

Plain and simple.

干净利落。

int[] array_sort = {5, 12, 3, 21, 8, 7, 19, 102, 201 };

List<Integer> odd = new ArrayList<Integer>();
List<Integer> even = new ArrayList<Integer>();
for (int i : array_sort) {
    if ((i & 1) == 1) {
        odd.add(i);
    } else {
        even.add(i);
    }
}
Collections.sort(odd);
Collections.sort(even);
System.out.println("Odd:" + odd);
System.out.println("Even:" + even);

回答by Colin Hebert

There are some things to know first :

首先要了解一些事情:

  • You must initialize an array before using it. For example int[] even_sort = new int[3];
  • In java arrays have a static size. That means that you won't be able to add as many elements as you want. You have to choose a size before. You should take a look at Java Collections, it's a good way to get rid of this "rule" the java way.
  • The Arrays.sort()method apply on arrays only. Here array_sort[i]is an int
  • Arrays.sort()sorts an array but doesn't return anything.
  • 您必须在使用数组之前对其进行初始化。例如int[] even_sort = new int[3];
  • 在 java 数组中有一个静态大小。这意味着您将无法添加任意数量的元素。您必须先选择尺寸。您应该看看 Java Collections,这是一种以 Java 方式摆脱这种“规则”的好方法。
  • Arrays.sort()方法仅适用于数组。这array_sort[i]是一个int
  • Arrays.sort()对数组进行排序但不返回任何内容。


If you really want to use arrays (but you shouldn't) you can do something like this to resize one :

如果你真的想使用数组(但你不应该)你可以做这样的事情来调整一个:

int[] even_sort = new int[3]{1, 2, 3};
int[] temp = new int[4];
System.arraycopy(even_sort, 0, temp, 0, even_sort.length);
even_sort = temp;
even_sort[3] = 4;


Another way would be creating an utility method which uses reflection to create the new array :

另一种方法是创建一个实用方法,它使用反射来创建新数组:

import java.lang.reflect.Array;

public Object resizeArray(Object originalArray, int newSize){
    int originalSize = Array.getLength(originalArray);
    Class arrayType = originalArray.getClass().getComponentType();
    Object newArray = Array.newInstance(arrayType, newSize);
    System.arraycopy(originalArray, 0, newArray, 0, Math.min(originalSize, newSize));
    return newArray;
}


So if you still want to use array for some reasons (but you still shouldn't) here is a code to filter, resize and sort your array.

因此,如果您出于某些原因仍然想使用数组(但您仍然不应该),这里有一个代码来过滤、调整大小和排序您的数组。

int[] arrayToFilterAndSort = {5, 12, 3, 21, 8, 7, 19, 102, 201};
int[] sortedEvens = new int[0];
for(int current : arrayToFilterAndSort){
    if((current & 1) == 1){
        sortedEvens = resizeArray(sortedEvens, sortedEvens.length + 1);
        sortedEvens[sortedEvens.length - 1] = current;
    }
}
Arrays.sort(sortedEvens);


Resources :

资源 :

回答by polygenelubricants

It's simple to do this using Guava.

使用 Guava 很容易做到这一点。

  • Use Ints.asListto create a List<Integer>live view of an int[]
  • Define a Function<Integer,Boolean> isOdd
  • Use Orderingthat compares onResultOf(isOdd), naturally (i.e. falsefirst, then true)
  • If necessary, compoundthat with an Ordering.natural()
  • 使用Ints.asList创建List<Integer>的实时取景int[]
  • 定义一个 Function<Integer,Boolean> isOdd
  • 自然地使用Ordering比较onResultOf(isOdd)(即false首先,然后true
  • 如果必要的话,compound该用Ordering.natural()

Here's the snippet:

这是片段:

    int[] nums = {5,12,3,21,8,7,19,102,201};
    Function<Integer,Boolean> isOdd = new Function<Integer,Boolean>() {
        @Override
        public Boolean apply(Integer i) {
            return (i & 1) == 1;
        }
    };
    Collections.sort(
        Ints.asList(nums),
        Ordering.natural().onResultOf(isOdd)
            .compound(Ordering.natural())
    );
    System.out.println(Arrays.toString(nums));
    // [8, 12, 102, 3, 5, 7, 19, 21, 201]

Note that all the even numbers show up first, then all the odd numbers. Within each group, the numbers are sorted naturally.

请注意,首先显示所有偶数,然后显示所有奇数。在每个组内,数字自然排序。

External links

外部链接

回答by Stephen C

Your question as stated doesn't make sense, and neither does the code. So I'm guessing that you want to separate the elements of an array into two arrays, one containing odds and the other evens. If so, do it like this:

您所说的问题没有意义,代码也没有意义。所以我猜你想把一个数组的元素分成两个数组,一个包含赔率,另一个包含偶数。如果是这样,请这样做:

int[] input = {5, 12, 3, 21, 8, 7, 19, 102, 201};
List<Integer> evens = new ArrayList<Integer>();
List<Integer> odds = new ArrayList<Integer>();
for (int i : input) {
    if (i % 2 == 0) {
        evens.add(i);
    } else {
        odds.add(i);
    }
}

You can then convert a list of Integer to a sorted array if int as follows:

然后,您可以将 Integer 列表转换为排序数组 if int ,如下所示:

List<Integer> list ...
int[] array = new int[list.size()];
for (int i = 0; i < array.length; i++) {
    array[i] = list.get(i);
}
Arrays.sort(array);

or if a sorted List<Integer>is what you need, just do this:

或者,如果List<Integer>您需要sorted ,请执行以下操作:

Collections.sort(list);

回答by java baby

package com.java.util.collection;

import java.util.Arrays;

/**
 * Given n random numbers. Move all even numbers on left hand side and odd numbers on right hand side and 
 * then sort the even numbers in increasing order and odd numbers in decreasing order For example, 
 * i/p : 3 6 9 2 4 10 34 21 5 
 * o/p: 2 4 6 10 34 3 5 9 21
 * @author vsinha
 *
 */
public class EvenOddSorting {

    public static void eventOddSort(int[] arr) {
        int i =0;
        int j =arr.length-1;
        while(i<j) {
            if(isEven(arr[i]) && isOdd(arr[j])) {
                i++;
                j--;
            } else if(!isEven(arr[i]) && !isOdd(arr[j])) {
                swap(i,j,arr);
            } else if(isEven(arr[i])){
                i++;
            } else{
                j--;
            }

        }   
        display(arr);
        // even number sorting
        Arrays.sort(arr,0,i);
        Arrays.sort(arr,i,arr.length);
        // odd number sorting
        display(arr);

    }

    public static void display(int[] arr) {
        System.out.println("\n");
        for(int val:arr){
            System.out.print(val +"  ");
        }
    }

    private static void swap(int pos1, int pos2, int[] arr) {
        int temp = arr[pos1];
        arr[pos1]= arr[pos2];
        arr[pos2]= temp;
    }

    public static boolean isOdd(int i) {
        return (i & 1) != 0;
    }
    public static boolean isEven(int i) {
        return (i & 1) == 0;
    }
    public static void main(String[] args) {
        int arr[]={3, 6, 9 ,2, 4, 10, 34, 21, 5};
        eventOddSort(arr);
    }
}

回答by facebook-1077138395637126

package srikanth dukuntla;

public class ArrangingArray {

    public static void main(String[] args) {
        int j=0;
        int []array={1,2,3,5,4,55,32,0};
        System.out.println(array.length);
        int n=array.length/2;
        for (int i=0; i<array.length; i++){

            if(array[i]%2!=0){
                j=1;

                int temp=array[array.length-j];
            if(temp % 2!=0){

                while((array[array.length-(j+1)]%2!=0) && (array.length-(j+1)>n)){
                        j++;
                }
                    int temp2=array[array.length-(j+1)];
                     array[array.length-(j+1)] =array[i];
                      array[i]=temp2;

                }else // inner if
                {
                 array[array.length-j] =array[i];
                  array[i]=temp;
                }

            }else //main if
            {
                //nothing needed

            }

        }

        for(int k=0;k<array.length;k++) {
            System.out.print(" "+ array[k]);
        }

    }

}

回答by shimy

List < Integer > odd = new ArrayList < Integer > ();

List < Integer > even = new ArrayList < Integer > ();

int a [] = {0,2,3,98,1,6546,45323,1134564};

int i;
for (i = 0; i < a.length; i++) {

    if (a[i] % 2 == 0) {

        even.add(a[i]);

    } else {

        odd.add(a[i]);

    }
}

System.out.print("Even: " + even + "\n");
System.out.print("Uneven: " + odd + "\n");
}
}