[英]Sort all even numbers in ascending order and then sort all odd numbers in descending order in a collection
[英]How to print even numbers in ascending order and odd numbers in descending order without using collection
輸入:
10
3 1 45 67 2 56 89 22 11 69
輸出(我想要的):
2 22 56
89 69 67 45 11 3 1
我想在不使用 collection 的情況下按升序打印偶數和按降序打印奇數,因為我不知道 collection 。 在這里幫我看看如何按降序打印奇數我可以打印到偶數
代碼:
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]);
}
}
}
}
代碼:
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] + " ");
}
}
}
}
輸出:
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
解釋:
由於數組已經排序(按升序),首先打印出偶數。
然后以相反的方向(降序)遍歷數組,並打印出奇數。
使用相同的 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.