思路:
新建brr、crr两个数列,分别存放目标数列的升序和降序。
判断是否为升序:
遍历arr,判断arr与brr相应位置上的元素是否相等。若出现不相等的情况,则不是升序;
判断是否为降序:
同上;
代码的实现:
package com.atchensong.forth;
import java.util.Scanner;
/**
* @author Chensong
* @description
* @create 2022-03-08 21:08
*/
public class TestF1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
int[] brr = new int[n];
int[] crr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt();
brr[i] = arr[i];
crr[i] = arr[i];
}
//brr升序
for (int i = 0; i < brr.length; i++) {
for (int j = 0; j < brr.length - i - 1; j++) {
if (brr[j] > brr[j + 1]) {
int t = brr[j];
brr[j] = brr[j + 1];
brr[j + 1] = t;
}
}
}
//crr降序
for (int i = 0; i < crr.length; i++) {
for (int j = 0; j < crr.length - i - 1; j++) {
if (crr[j] < crr[j + 1]) {
int t = crr[j];
crr[j] = crr[j + 1];
crr[j + 1] = t;
}
}
}
//开始判断:
int numb = 0, numc = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == brr[i])
numb++;
if (arr[i] == crr[i])
numc++;
}
if (numb == n || numc == n)
System.out.println("sorted");
else
System.out.println("unsorted");
}
}