错误的逻辑
OP 的代码由于
而失败
}else if (A[i]>=A[i+1]){
tempdcr++;
应该是
}
if (A[i]>=A[i+1]) {
tempdcr++;
考虑A[i]==A[i+1] 的情况,两个计数器都应该递增。
垃圾值
缺少初始化@kaylum。
// int tempcr, tempdcr;
int tempcr = 0;
int tempdcr = 0;
替代方法:
有四种可能
-
数组在每个位置 - 或长度为 0 处都有相同的值。
-
数组正在升序。 A[i] >= A[i-1] 代表所有 i > 0 并且长度大于 0。
-
数组正在下降。 A[i] <= A[i-1] 代表所有 i > 0 并且长度大于 0。
-
以上都不是。
只需循环并调整两个标志。 int tempcr, tempdcr; 不需要计数器。
int Is_Sorted(const int* A, int n) {
bool isAscending = true;
bool isDescending = true;
for (int i = 1; i<n; i++) { // start at 1
if (A[i] < A[i-1]) isAscending = false;
if (A[i] > A[i-1]) isDescending = false;
}
if (isAscending && isDescending) {
return TBD; // Unsure what OP wants here
}
if (isAscending) {
return 1;
}
if (isDescending) {
return -1;
}
return 0;
}
可能会进行一些简化和一些微优化,但需要澄清一个清晰的方法。
太有趣了。
如果int a[]不是常数,我们每次迭代只能使用1个测试而不是3个:test i,is less,is more em> 以上代码。
首先从头到尾寻找不等式。第一个元素被调整为与最后一个元素不同。
如果我们遍历整个列表,我们就完成了,否则列表的第一部分与最后一个元素不同。
如果最后一个比较是升序,则将第一个元素设置为 INT_MAX 并朝开头搜索非升序对。
否则
如果最后一个比较是降序的,则将第一个元素设置为 INT_MIN 并在开头搜索非降序对。
发现发生比较失败时,要么数组无序,要么我们处于开头。如果在开头,则处理该特殊情况。
在任何情况下,每次迭代只有 1 个比较。
#define ASCENDING 1
#define DESCENDING -1
#define UNORDERED 0
#define ALLSAME 1 // Adjust as desired
#define SHORT_LENGTH 1 // Adjust as desired
int is_sorted(size_t n, int *a) {
if (n <= 1) {
return n ? ALLSAME : SHORT_LENGTH;
}
int last = a[--n];
int first = a[0];
a[0] = !last;
while (last == a[--n]) {
;
}
a[0] = first; // restore
if (n == 0) {
if (a[0] < a[1]) {
return ASCENDING;
}
if (a[0] > a[1]) {
return DESCENDING;
}
return ALLSAME;
}
if (a[n - 1] < a[n]) {
// Only ascending, unordered possible
a[0] = INT_MAX;
while (a[n - 1] <= a[n]) {
n--;
}
a[0] = first; // restore
if (a[n - 1] <= a[n]) {
return ASCENDING;
}
} else {
// Only descending, unordered possible
a[0] = INT_MIN;
while (a[n - 1] <= a[n]) {
n--;
}
a[0] = first; // restore
if (a[n - 1] <= a[n]) {
return DESCENDING;
}
}
return UNORDERED;
}
稍后我会进行更多测试。
如果数组是const,每个循环需要2次测试。