如何查找数字序列是升序还是降序

How to find if sequence of numbers is ascending or descending

我真的在过去几个小时(+ - 10 小时)中为这项任务而苦苦挣扎。 编写一个程序,读取一个整数序列,如果序列是有序的(升序或降序)则输出 true,否则输出 false。请记住,如果一个数字与后面的数字具有相同的值,则不会破坏顺序。

class Main {
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    int a = scanner.nextInt();

    int i = 0;
    boolean isOrdered = true;
    int previous = 0;
    int current = 0;

    while (a != 0) {
        while (i > a) {
            current = scanner.nextInt();   
            if (current < previous) {
                isOrdered = false;
            }else {
                previous = current;
                i++;
            }                
        }
    }
}

}

这是一个紧凑的小方法。效率不高,因为它没有短路逻辑。看看你能不能理解它是如何工作的。

static boolean isOrdered(int... input) {
    int[] counts = new int[3];
    for (int i = 1; i < input.length; i++)
        ++counts[1 + Integer.signum(Integer.compare(input[i - 1], input[i]))];
    return (counts[0] == 0 || counts[2] == 0);
}

测试

System.out.println(isOrdered(1, 2, 4, 8, 16, 32));   // true (ascending, no equals)
System.out.println(isOrdered(1, 1, 2, 3, 5, 8, 13)); // true (ascending, with equals)
System.out.println(isOrdered(9, 7, 7, 5, 3, 3, 1));  // true (decending, with equals)
System.out.println(isOrdered(5, 5, 5, 5, 5, 5));     // true (all equal)
System.out.println(isOrdered(1, 3, 5, 2, 9, 11));    // false

输出

true
true
true
true
false

您需要检测数字是否同时升序和降序。如果两者都需要,你需要returnfalse,否则你returntrue.

为此,您需要两个 boolean 变量。

伪代码:

isAscending = false
isDescending = false
loop values:
    if value > previousValue:
        isAscending = true
    else if value < previousValue:
        isDescending = true
if isAscending and isDescending:
    return false
return true

这基本上就是我的 所做的,使用代码技巧。