1. 题目
判断整数数组元素是否已经按升序排序
2. 解题思路
读取count个整数,依次存放在数组arr中,设计一个isSorted函数,将arr数组里的任意相邻整数比较:
如果出现后者比前者小的情况,则返回false
如果全部后者比前者大的情况,则返回True
3. 编程
3.1 使用C++语言
程序:
#include <stdio.h>
#define maxSize 1000
bool isSorted(int *arr, int n) {
int i, j;
for (i = 0; i < n; ++i) {
for (j = i+1; j < n; ++j) {
printf("compare %d %d\n",*(arr+i),*(arr+j));
if (*(arr+i) > *(arr+j)) {
return false;
}
}
}
return true;
}
int main() {
int num, count = 0;
int arr[maxSize];
scanf("%d", &count);
for(int i = 0; i < count; i ++)
{
scanf("%d", &arr[i]) ;
}
for(int i = 0; i < count; i ++) printf("the %d th item of arr is %d\n",i,arr[i]);
// while (scanf("%d", &num) != EOF) {
// arr[count++] = num;
// }
bool flag = isSorted(arr, count);
if (flag) {
printf("YES\n");
} else {
printf("NO\n");
}
return 0;
}
测试:
如果输入格式采用
while (scanf("%d", &num) != EOF)
始终无法结束输入采集,于是我修改了输入格式。
YES结果的测试:
C:\Users\zhangyy\CLionProjects\Ctest\cmake-build-debug\Ctest.exe
3
5 6 7
the 0 th item of arr is 5
the 1 th item of arr is 6
the 2 th item of arr is 7
compare 5 6
compare 5 7
compare 6 7
YES
Process finished with exit code 0
NO结果的测试:
C:\Users\zhangyy\CLionProjects\Ctest\cmake-build-debug\Ctest.exe
3
5 8 4
the 0 th item of arr is 5
the 1 th item of arr is 8
the 2 th item of arr is 4
compare 5 8
compare 5 4
NO
Process finished with exit code 0
3.2 使用python3语言
程序
import sys
cnt = 0
flag = True
for line in sys.stdin:
if cnt > 0:
a = b
b = line.split()[0]
if a > b:
flag = False
else:
b = line.split()[0]
cnt += 1
if flag:
print("YES")
else:
print("NO")
测试
我是用pycharm编辑器调试的,输入每个整数换行,全部输入完成后,按“ctrl+D”结束输入。
YES结果测试
C:\Users\zhangyy\PycharmProjects\ACM_Test\venv\Scripts\python.exe C:\Users\zhangyy\PycharmProjects\ACM_Test\main.py
3
4
6
^D
YES
Process finished with exit code 0
NO结果测试
C:\Users\zhangyy\PycharmProjects\ACM_Test\venv\Scripts\python.exe C:\Users\zhangyy\PycharmProjects\ACM_Test\main.py
3
5
2
^D
NO
Process finished with exit code 0
4 最后
这是一道用来练手的ACM简单题,主要熟悉输入输出格式和典型代码形式。