Wrong logic
OP's code fails due to
}else if (A[i]>=A[i+1]){
tempdcr++;
should be
}
if (A[i]>=A[i+1]) {
tempdcr++;
Consider the case when A[i]==A[i+1], both counters should increment.
Junk Values
Missing initialization @kaylum.
// int tempcr, tempdcr;
int tempcr = 0;
int tempdcr = 0;
Alternative approach:
There are 4 possibilities
Array has the same value value every where - or is of length 0.
Array is ascending. A[i] >= A[i-1] for all i > 0 and length is more than 0.
Array is descending. A[i] <= A[i-1] for all i > 0 and length is more than 0.
None of the above.
Simply loop and adjust two flags. int tempcr, tempdcr; counters not needed.
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;
}
Simplifications and some micro optimization possible, but something to clarify a clear approach.
Too much fun.
If int a[] is not constant, we can only use 1 test per iteration instead of 3: test i, is less, is more of the above code.
First look for inequality from the end toward the beginning. The first element is adjusted to be different from the last.
If we walk the entire list, we are done, otherwise the first part of the list differs from the last element.
If the last compare is ascending, set the first element to INT_MAX and search toward the beginning for a non-ascending pair.
Otherwise
If the last compare is descending, set the first element to INT_MIN and search toward the beginning for a non-descending pair.
Upon finding a compare failure occurs, either the array is unordered or we are at the beginning. If at the beginning, handle that special case.
In any case, only 1 compare per iteration.
#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;
}
I'll do some more testing later.
If the array is const, need 2 test per loop.
tempcrandtemdcrare not initialised. Means that they can contain any garbage value to start off with.ninIs_Sorted(int* A, int n)is not used in the function.