簡體   English   中英

在循環中檢查數組是升序還是降序

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

我需要編寫一個程序來檢查男孩(3)是按高度升序還是降序排列的。

我可以使用3scanner.nextInt()

int a = scanner.nextInt();

比使用 if 語句:

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

它工作得很好。

我也可以創建一個數組並檢查它,但這並不有趣。 但我想嘗試使用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);

在這里,我將boyHeight的輸入值分配給a變量並將其與下一個掃描值進行比較,但我總是得到錯誤的true結果。

這是一種確定所有三個是否按降序、升序或根本不按順序的方法。

 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.   }

幾點注意事項:

  • 第 2 行:這被硬編碼為 3,如果您想與 4 或其他數字進行比較,顯然它不會起作用
  • 第 3-5 行:也硬編碼為 3,但可以很容易地移入循環
  • 第 7 行:如果項目 0 大於 1,並且 1 大於 2,這顯然是“降序”。 這可以重新設計以適應循環,但這樣看可能更清楚。
  • 第9行:與第7行類似,只是比較另一個方向
  • 第 12 行:這是混合排序的情況,既不升也不降

如果你想使用循環,這里有一個替換第 2-5 行的編輯:

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

在循環中檢查數組升序還是降序

我想嘗試for掃描循環內的輸入值來解決它

下面的解決方案允許在使用硬編碼條件的情況下確定數組是否為任意長度數組的順序。

請注意,將用戶輸入存儲到數組中同時檢查該數組是否有序違反了第一個 SOLID 原則 - 單一責任原則 正確的方法是首先從控制台讀取數組數據(這很簡單),然后確定這個數組是否是有序的——這是這個答案的重點。

無論數組中有多少元素,都可能存在以下情況:

  • 數組按升序排序;

  • 數組按降序排列;

  • 數組是無序的;

  • 由於允許值相等,因此可能存在所有元素相等的情況,即我們不能說數組是無序的,但同時它既不是升序也不是降序。

我還假設給定將包含至少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
}

輸出:

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

另一種即時執行此操作的方法是

  1. 讀取元素個數(輸入驗證至少2個值)
  2. 檢查前 2 個值以獲取訂單
  3. 迭代其余元素並檢查順序是否相同
  4. 顯示結果
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