[英]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 .我想在不使用 collection 的情况下按升序打印偶数和按降序打印奇数,因为我不知道 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:使用相同的 for 循环反转标志和打印:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.