开发者

Array even & odd sorting

开发者 https://www.devze.com 2023-01-20 09:52 出处:网络
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

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

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


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


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:

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:

Collections.sort(list);


It's simple to do this using Guava.

  • Use Ints.asList to create a List<Integer> live view of an int[]
  • Define a Function<Integer,Boolean> isOdd
  • Use Ordering that compares onResultOf(isOdd), naturally (i.e. false first, then true)
  • If necessary, compound that with an 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

  • polygenelubricants.com - Writing more elegant comparison logic with Guava's Ordering


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.

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 :

  • oracle.com - Arrays tutorial
  • oracle.com - Collections tutorial
  • javadoc - Arrays.sort()


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


int arr[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << "The Even no are : \n";
for (int i = 1; i <= 10; i++) // for start for only i....(even nos)
{
    if (i % 2 == 0)
    {
        cout << i;
        cout << " ";
    }
}
cout << "\nThe Odd no are : \n";
for (int j = 1; j <= 10; j++) // for start for only j....(odd nos)
{
    if (j % 2 != 0)
    {
        cout << j;
        cout << " ";
    }`enter code here`
}


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

    }

}


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号