[英]How to generate an array of pseudo-random, unique, sorted integers without using an if statement?
[英]How to check if an integer array is sorted without using an "if" statement?
如何更改此代碼以在不使用 if 語句的情況下工作? 我嘗試使用 while 循環,但它不起作用。 從那以后,我意識到我錯誤地使用了 while 循環。 那我該怎么做呢? (使用Java)
public class isSorted {
public static void main(String[] args) {
//declaring array literal
double a[] = {1.5, 4.3, 7.0, 19.5, 25.1, 46.2};
int L = a.length;
boolean isSorted = false;
for (double i = 0; i < L; i++) {
if (a[(int) i] < a[(int) (i + 1)]) {
isSorted = true;
}
break;
}
System.out.println(isSorted);
}
}
一種方法是這樣的:
double a[] = {1.5, 4.3, 7.0, 19.5, 25.1, 46.2};
int i = 0;
while (i < a.length - 1 && a[i] <= a[i + 1])
i++;
boolean isSorted = i >= a.length - 1;
System.out.println(isSorted);
基本上你檢查當前元素是否小於或等於下一個元素,直到你發現不匹配或整個數組被解析。 然后檢查i
變量的值將告訴您數組是否已排序。
要檢查降序,只需將條件更改為:
a[i - 1] >= a[i]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.