简体   繁体   English

在循环中检查数组是升序还是降序

[英]Checking if an Array is in Ascending or Descending order in a loop

I need to write a program that checks if the boys (3) are arranged in ascending or descending order by height.我需要编写一个程序来检查男孩(3)是按高度升序还是降序排列的。

I can use 3 times scanner.nextInt() :我可以使用3scanner.nextInt()

int a = scanner.nextInt();

than use if statement :比使用 if 语句:

if (a >= b && b >= c || c >= b && b >= a) {
    System.out.println("true");
} else {
    System.out.println("false");
}

And it's work perfectly.它工作得很好。

I also can create an array and check it, but it's not interesting.我也可以创建一个数组并检查它,但这并不有趣。 But I want to try to solve it using for loop for scanning input values within loop and check conditions:但我想尝试使用for循环扫描循环内的输入值并检查条件来解决它:

final int numberOfBoys = 3;
boolean result = false;
    
for (int i = 0; i < numberOfBoys; i++) {
    int boyHeight = scanner.nextInt();
    int a = boyHeight;
    if (a >= boyHeight || a <= boyHeight) {
        result = true;
    }
}
    
System.out.println(result);

Here I assigned input value of boyHeight to a variable and compare it with next scanning value, but I always get true result which is wrong.在这里,我将boyHeight的输入值分配给a变量并将其与下一个扫描值进行比较,但我总是得到错误的true结果。

Here is a way to determine if all three are in descending order, ascending order, or not in order at all.这是一种确定所有三个是否按降序、升序或根本不按顺序的方法。

 1.   Scanner scanner = new Scanner(System.in);
 2.   int[] heights = new int[3];
 3.   heights[0] = scanner.nextInt();
 4.   heights[1] = scanner.nextInt();
 5.   heights[2] = scanner.nextInt();
 6.   
 7.   if (heights[0] >= heights[1] && heights[1] >= heights[2]) {
 8.      System.out.println("descending order");
 9.   } else if (heights[0] <= heights[1] && heights[1] <= heights[2]) {
10.      System.out.println("ascending order");
11.   } else {
12.      System.out.println("not in order");
13.   }

A few notes:几点注意事项:

  • line 2: this is hard-coded to 3, obviously it wouldn't work if you want to compare with 4 or some other number第 2 行:这被硬编码为 3,如果您想与 4 或其他数字进行比较,显然它不会起作用
  • lines 3-5: also hard-coded to 3, but easily could be moved into a loop第 3-5 行:也硬编码为 3,但可以很容易地移入循环
  • line 7: if item 0 is larger than 1, and 1 is larger than 2, that's clearly "descending".第 7 行:如果项目 0 大于 1,并且 1 大于 2,这显然是“降序”。 This could be reworked to fit with a loop, but it's perhaps clearer to see this way.这可以重新设计以适应循环,但这样看可能更清楚。
  • line 9: similar to 7, just compare the other direction第9行:与第7行类似,只是比较另一个方向
  • line 12: this is the case for mixed ordering, neither ascending nor descending第 12 行:这是混合排序的情况,既不升也不降

If you want to use a loop, here's an edit to replace lines 2-5:如果你想使用循环,这里有一个替换第 2-5 行的编辑:

int totalToCheck = 3;
int[] heights = new int[totalToCheck];
for (int i = 0; i < totalToCheck; i++) {
    heights[i] = scanner.nextInt();
}

Checking if an Array is in Ascending or Descending order in a loop在循环中检查数组升序还是降序

I want to try solve it using for scanning input values within loop我想尝试for扫描循环内的输入值来解决它

Solution below allow to determine whether array the order of an array of an arbitrary length without using hard-coded conditions .下面的解决方案允许在使用硬编码条件的情况下确定数组是否为任意长度数组的顺序。

Note that storing the user input into an array simultaneously with checking if this array is order violate the first SOLID principle - the Single responsibility principle .请注意,将用户输入存储到数组中同时检查该数组是否有序违反了第一个 SOLID 原则 - 单一责任原则 The correct way to do that is to first read the array data from the console (which is pretty trivial) and then determine whether this array is ordered - that is the focus of this answer.正确的方法是首先从控制台读取数组数据(这很简单),然后确定这个数组是否是有序的——这是这个答案的重点。

Regardless of the number of elements in the array there could be the following cases:无论数组中有多少元素,都可能存在以下情况:

  • Array is sorted in Ascending order;数组按升序排序;

  • Array is sorted in Descending order;数组按降序排列;

  • Array is unordered ;数组是无序的;

  • Since equal values are allowed there could be the case when all elements are equal, ie we can't say array is unordered, but at the same it is neither ascending, no descending.由于允许值相等,因此可能存在所有元素相等的情况,即我们不能说数组是无序的,但同时它既不是升序也不是降序。

I'm also making an assumption that the given will contain at least 1 element.我还假设给定将包含至少1元素。

public static void determineArrayOrder(int[] arr) {
    
    boolean isAsc = arr[0] < arr[arr.length - 1]; // if array is sorted in ascending order the first element has to be less than the last element
    int previous = arr[0]; // variable that would hold the value of the previously encountered element
    
    for (int i = 1; i < arr.length; i++) { // iteration starts from 1 because `previous` has been initialized with the value of the element at index 0
        int next = arr[i];
        
        if (next < previous && isAsc || next > previous && !isAsc) { // the order doesn't match
            System.out.println("Array is unordered");
            return;
        }
        previous = next;
    }
    // printing the result
    if (arr[0] == arr[arr.length - 1]) {
        System.out.println("impossible to determine the order");
    } else if (isAsc) {
        System.out.println("Array is sorted in Ascending order");
    } else {
        System.out.println("Array is sorted in Descending order");
    }
}

main()

public static void main(String[] args) {
    determineArrayOrder(new int[]{1, 2, 3, 3, 3}); // ASC
    determineArrayOrder(new int[]{7, 5, 3, 3, 5}); // unordered
    determineArrayOrder(new int[]{7, 8, 9, 8, 8}); // unordered
    determineArrayOrder(new int[]{7, 5, 3, 3, 1}); // DSC
    determineArrayOrder(new int[]{9, 9, 9, 9, 9}); // impossible to determine the order
}

Output:输出:

Array is sorted in Ascending order
Array is unordered
Array is unordered
Array is sorted in Descending order
impossible to determine the order

Another way of doing this on the fly is另一种即时执行此操作的方法是

  1. Read the number of elements (input validation at least 2 values)读取元素个数(输入验证至少2个值)
  2. Check first 2 values to get the order检查前 2 个值以获取订单
  3. Iterate the rest of elements and check if the order is the same迭代其余元素并检查顺序是否相同
  4. Display the result显示结果
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Input numbers: ");
    int numberOfBoys = scanner.nextInt(); // Read the number of elements in the array
    if (numberOfBoys < 2) { // Validate the input
        System.out.println("Invalid input");
    }
    boolean isAsc = false; // Assume that the sequence is DESC
    boolean isValid = true; // Assume that the sequence is valid
    int previousRead = scanner.nextInt(); // Read first value
    int currentRead = scanner.nextInt(); // Read second value

    if (previousRead < currentRead) { // Check if the first 2 values are ASC
        isAsc = true; // Correct our assumption
    }

    previousRead = currentRead; // Swap the values to prepare for the next read
    // Iterate through the rest of the sequence
    for (int i = 0; i < numberOfBoys - 2; i++) {
        currentRead = scanner.nextInt(); // Read the next value
        // Check if the new value respect the order
        isValid = isAsc ? currentRead >= previousRead : currentRead <= previousRead;
        // if the new value does not follow the order,
        // breaks the loop because we already know the answer and
        // there is no point in reading the rest of the values
        if (!isValid) {
            break;
        }
        previousRead = currentRead; // Swap the values to prepare for the next read
    }

    // Print the conclusion
    if (isValid) {
        if (isAsc) {
            System.out.println("ASC");
        } else {
            System.out.println("DESC");
        }
    } else {
        System.out.println("Unsorted");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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