数组是以降序,升序还是无序排序?

时间:2019-05-08 16:51:15

标签: java arrays

我想编写代码来告诉我数组是否已排序。如果数组是:

  
      
  • 按升序排列,即。 (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-block中更改条件。

1 个答案:

答案 0 :(得分:1)

由于要覆盖循环中的结果变量,因此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;
    }
}
相关问题