简体   繁体   English

如何在Java中将数组中的数字排序为两个不同的数组?

[英]How do I sort numbers from an array into two different arrays in java?

I have to create a program that takes an array of both even and odd numbers and puts all the even numbers into one array and all the odd numbers into another. 我必须创建一个程序,该程序接受一个由偶数和奇数组成的数组,并将所有偶数放入一个数组,并将所有奇数放入另一个数组。 I used a for loop to cycle through all the numbers and determine if they are even or odd, but the problem I'm having is that since the numbers in the original array are random, I don't know the size of either the even or the odd array and therefore can't figure out how to assign numbers in the original array to the even/odd arrays without having a bunch of spots left over, or not having enough spots for all the numbers. 我使用了for循环遍历所有数字并确定它们是偶数还是奇数,但是我遇到的问题是,由于原始数组中的数字是随机的,因此我不知道偶数的大小或奇数数组,因此无法弄清楚如何将原始数组中的数字分配给偶数/奇数数组,而不会留下一堆斑点或没有足够的斑点来容纳所有数字。 Any ideas? 有任何想法吗?

Try using an ArrayList. 尝试使用ArrayList。 You can use 您可以使用

num % 2 == 0

to see if num is even or odd. 查看num是偶数还是奇数。 If it does == 0 then it is even, else it is odd. 如果它== 0,则为偶数,否则为奇数。

List<Integer> odds = new ArrayList(); 
List<Integer> evens = new ArrayList();

for (int i = 0; i< array.length; i++) {
   if (array[i] % 2 == 0) {
      evens.add(array[i]);
   }
   else {
       odds.add(array[i]);
   }
}

to convert the ArrayLists back to arrays you can do 可以将ArrayLists转换回数组

int[] evn = evens.toArray(new Integer[evens.size()]);

(Note: untested code so there could be a few typos) (注意:未经测试的代码,因此可能会有一些输入错误)

EDIT: 编辑:

If you are not allowed to use ArrayLists then consider the following that just uses Arrays. 如果不允许使用ArrayList,请考虑以下仅使用Arrays的情况。 It's not as efficient as it has to do two passes of the original array 它效率不如必须对原始数组进行两次遍历

int oddSize = 0; 
int evenSize = 0; 

for (int i = 0; i< array.length; i++) {
   if (array[i] % 2 == 0) {
      evenSize++;
   }
   else {
      oddSize++;
   }
}


Integer[] oddArray = new Integer[oddSize];
Integer[] evenArray = new Integer[evenSize];

int evenIdx = 0;
int oddIdx = 0;

for (int i = 0; i< array.length; i++) {
   if (array[i] % 2 == 0) {
      evenArray[evenIdx++] = array[i];
   }
   else {
      oddArray[oddIdx++] = array[i];
   }
}

You can do it without using arrays or any '%' Just a simple idea 您无需使用数组或任何'%'就可以做到这一点

input = new Scanner(System.in);
    int x;
    int y = 0; // Setting Y for 0 so when you add 2 to it always gives even
                // numbers
    int i = 1; // Setting X for 1 so when you add 2 to it always gives odd
                // numbers
    // So for example 0+2=2 / 2+2=4 / 4+2=6 etc..
    System.out.print("Please input a number: ");
    x = input.nextInt();

    for (;;) { // infinite loop so it keeps on adding 2 until the number you
                // input is = to one of y or i
        if (x == y) {
            System.out.print("The number is even ");
            System.exit(0);
        }
        if (x == i) {
            System.out.print("The number is odd ");
            System.exit(0);
        }
        if (x < 0) {
            System.out.print("Invald value");
            System.exit(0);
        }
        y = y + 2;
        i = i + 2;

    }

}

Use a List instead. 请改用List Then you don't need to declare the sizes in advance, they can grow dynamically. 然后,您无需预先声明大小,它们可以动态增长。

You can always use the toArray() method on the List afterwards if you really need an array. 如果确实需要数组,则以后始终可以在List上使用toArray()方法。

The above answers are correct and describe how people would normally implement this. 上面的答案是正确的,并描述了人们通常如何实现这一点。 But the description of your problem makes me think this is a class assignment of sorts where dynamic lists are probably unwelcome. 但是您对问题的描述使我认为这是类的类分配,其中动态列表可能不受欢迎。

So here's an alternative. 所以这是另一种选择。

Sort the array to be divided into two parts - of odd and of even numbers. 将数组排序为两部分-奇数和偶数。 Then count how many odd/even numbers there are and copy the values into two arrays. 然后计算有多少个奇/偶数并将值复制到两个数组中。

Something like this: 像这样:

static void insertionSort(final int[] arr) {
    int i, j, newValue;
    int oddity;
    for (i = 1; i < arr.length; i++) {
        newValue = arr[i];
        j = i;
        oddity = newValue % 2;
        while (j > 0 && arr[j - 1] % 2 > oddity) {
            arr[j] = arr[j - 1];
            j--;
        }
        arr[j] = newValue;
    }

}

public static void main(final String[] args) {
    final int[] numbers = { 1, 3, 5, 2, 2 };
    insertionSort(numbers);

    int i = 0;
    for (; i < numbers.length; i++) {
        if (numbers[i] % 2 != 0) {
            i--;
            break;
        }
    }

    final int[] evens = new int[i + 1];
    final int[] odds = new int[numbers.length - i - 1];
    if (evens.length != 0) {
        System.arraycopy(numbers, 0, evens, 0, evens.length);
    }
    if (odds.length != 0) {
        System.arraycopy(numbers, i + 1, odds, 0, odds.length);
    }

    for (int j = 0; j < evens.length; j++) {
        System.out.print(evens[j]);
        System.out.print(" ");
    }
    System.out.println();
    for (int j = 0; j < odds.length; j++) {
        System.out.print(odds[j]);
        System.out.print(" ");
    }
}

Iterate through your source array twice. 遍历源数组两次。 The first time through, count the number of odd and even values. 第一次通过,计算奇数和偶数的数量。 From that, you'll know the size of the two destination arrays. 由此,您将知道两个目标数组的大小。 Create them, and take a second pass through your source array, this time copying each value to its appropriate destination array. 创建它们,然后第二遍遍您的源数组,这一次将每个值复制到其适当的目标数组。

I imagine two possibilities, if you can't use Lists, you can iterate twice to count the number of even and odd numbers and then build two arrays with that sizes and iterate again to distribute numbers in each array, but thissolution is slow and ugly. 我想像有两种可能,如果您不能使用列表,则可以迭代两次以计算偶数和奇数,然后构建具有该大小的两个数组,然后再次迭代以在每个数组中分配数字,但是这种解决方案既缓慢又丑陋。

I imagine another solution, using only one array, the same array that contains all the numbers. 我想象另一种解决方案,仅使用一个数组,即包含所有数字的同一数组。 You can sort the array, for example set even numbers in the left side and odd numbers in the right side. 您可以对数组进行排序,例如,在左侧设置偶数,在右侧设置奇数。 Then you have one index with the position in the array with the separation ofthese two parts. 然后,您将获得一个索引,其中索引在数组中的位置以及这两部分之间的间隔。 In the same array, you have two subarrays with the numbers. 在同一数组中,您有两个带有数字的子数组。 Use a efficient sort algorithm of course. 当然,请使用有效的排序算法。

Use following Code : 使用以下代码:

public class ArrayComparing {

    Scanner console= new Scanner(System.in);
    String[] names;
    String[] temp;
    int[] grade;

    public static void main(String[] args) {
        new ArrayComparing().getUserData();
    }

    private void getUserData() {
        names = new String[3];    
        for(int i = 0; i < names.length; i++) {
            System.out.print("Please Enter Student name: ");
            names[i] =console.nextLine();
            temp[i] = names[i];
        }

        grade = new int[3];    
        for(int i =0;i<grade.length;i++) {
            System.out.print("Please Enter Student marks: ");
            grade[i] =console.nextInt();
        }          

        sortArray(names);     
    }

    private void sortArray(String[] arrayToSort) {
        Arrays.sort(arrayToSort);

        getIndex(arrayToSort);
    }

    private void getIndex(String[] sortedArray) {
        for(int x = 0; x < sortedArray.length; x++) {
            for(int y = 0; y < names.length; y++) {
                if(sortedArray[x].equals(temp[y])) {
                    System.out.println(sortedArray[x] + " " + grade[y]);
                }
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM