Last time to write the data structure and algorithm in the sorting algorithm auxiliary tools class and three basic sorting, details see data structure and algorithm – sorting algorithm auxiliary tools to write and three basic sorting algorithms (Java implementation).

However, when I learned other algorithms later, I found that there was a BUG in the method of judging whether the array is ordered, because it can only judge whether the array is ordered in the case of order, but can not judge whether the array is ordered in the case of reverse order, so I enhanced and modified the method in the previous method.

  • If an array is ordered, return true. If an array is unordered, return false
Return true if an array is ordered, false if it is unordered@param arr
 * @return* /
public static boolean isOrderly(int[] arr) {
	if(isOrderAsc(arr) || isOrderDesc(arr)) {
		return true;
	}
	return false;
}

Return true if the array is in order, false if it is not in order@param arr
 * @return* /
private static boolean isOrderAsc(int[] arr) {
	for(int i=0; i < arr.length-1; i++) {if(arr[i] > arr[i+1]) {
			return false; }}return true;
}

Return true if the array is in order. Return false if the array is not in order@param arr
 * @return* /
private static boolean isOrderDesc(int[] arr) {
	for(int i = arr.length-1; i > 0; i--) {
		if(arr[i] > arr[i-1]) {
			return false; }}return true;
}
Copy the code