面试_算法_判断一个数组是否有序

54 阅读1分钟

递归搭配三元运算,比较巧妙,记录一下。

import java.util.Scanner;
 
class IsSort {
    public int isArrayInSortedOrder(int[] a, int index) {
        if (index == 1) {
            return 1;
        } else {
            return (a[index - 1] <= a[index - 2]) ? 0 : isArrayInSortedOrder(a, index - 1);   // 升序
        }
    }
}
 
public class Main {
 
    public static void main(String[] args) {
        // write your code here
        Scanner scan = new Scanner(System.in);
        int[] a = {1, 2, 3, 4, 5};
        IsSort sort = new IsSort();
        int res = sort.isArrayInSortedOrder(a, 5);
        System.out.println(res);
    }
}