简体   繁体   中英

How to print even numbers in ascending order and odd numbers in descending order without using collection

Input:

10
3 1 45 67 2 56 89 22 11 69

Output (what I want):

2 22 56 
89 69 67 45 11 3 1

I want to print even numbers in ascending order and odd numbers in descending order without using collection because i don't know collection . Help me here that how I can print odd number in descending order I am able to ptint till even number

Code:

import java.util.Arrays;
import java.util.Scanner;

class T {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner sc = new Scanner(System.in);
        System.out.println("enter a number");
        int n = sc.nextInt();

        int s[] = new int[n];
        int i;
        for (i = 0; i < n; i++) {
            int e = sc.nextInt();
            s[i] = e;
        }

        Arrays.sort(s);
        for (int j = 0; j < n; j++) {

            if (s[j] % 2 == 0) {
                System.out.println(s[j]);
            }
        }
    }
}

Code:

import java.util.Arrays;
import java.util.Scanner;

class T {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner sc = new Scanner(System.in);
        System.out.println("enter a number");
        int n = sc.nextInt();

        int s[] = new int[n];
        for (int i = 0; i < n; i++) {
            int e = sc.nextInt();
            s[i] = e;
        }

        Arrays.sort(s);
        // Even in ascending
        System.out.println("\nEven numbers in ascending order:");
        for (int j = 0; j < n; j++) {

            if (s[j] % 2 == 0) {
                System.out.print(s[j] + " ");
            }
        }

        // Odd in descending
        System.out.println("\nOdd numbers in descending order:");
        for(int j = (n -1); j >= 0; j--) {
            if (s[j] % 2 == 1) {
                System.out.print(s[j] + " ");
            }
        }
    }
}

Output:

enter a number
10
3 1 45 67 2 56 89 22 11 69

Even numbers in ascending order:
2 22 56 
Odd numbers in descending order:
89 69 67 45 11 3 1 

Explanation:

Since the array is already sorted (in ascending order), print out the even numbers first.
Then traverse the array in the opposite direction (desc order), and print out the odd numbers.

Reverse flag and print using same for loop:

int x = 0;

for (int j = 0; j < n; j++) {

    if (s[j] % 2 == x)
        System.out.println(s[j]);

    if (j == n - 1 && x == 0) {
        x = 1;
        j = 0;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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