![](/img/trans.png)
[英]check an array whether this is sorted ascending/descending and they are increasing/decreasing with a fixed value
[英]Is the array sorted in decreasing, increasing or no order?
我想編寫代碼來告訴我數組是否已排序。 如果數組是:
- 以升序排序,即。 (1,2,3,4,5),打印1。
- 以降序排序,即(5,4,3,2,1),打印-1。
- 無訂單(1,2,1,4,1),打印0。
public static int isSorted(int[] a) {
int result=0;
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]){
result=-1;
}else if (a[i] < a[i + 1] ) {
result=1;
}else{
result=0;
}
}
return result;
}
public static void main(String[] args) {
int[] a = { 9, 10, 9, 10, 12 };
System.out.println(isSorted(a));
}
}
我的結果現在不是我期望的結果,例如現在的順序[9,10,9,10,12]應該打印0,但我得到1。
有人可以幫幫我嗎? 我認為我需要在if / else塊中更改條件。
因為您要覆蓋循環中的result變量, result
只代表最后的檢查。 在這種情況下10 <=> 12。
嘗試此操作,最后進行檢查。
public static int isSorted(int[] a) {
boolean ascending = false;
boolean descending = false;
for (int currentIndex = 0, nextIndex = 1; nextIndex < a.length; currentIndex++, nextIndex++) {
if (a[currentIndex] > a[nextIndex]) {
descending = true;
} else if (a[currentIndex] < a[nextIndex]) {
ascending = true;
}
}
if ((descending && ascending) || (!descending && !ascending)) {
return 0;
} else if (descending) {
return -1;
} else {
return 1;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.