I need to write a function which checks if the elements in an array are in a monotonous order, I wrote the following program which works for some values but it doesn't work for others. For the current array the output is: "The elements are not sorted", and it should be "The array is decreasing". Any ideas? Also, I'm not sure if I used the correct way of updating the loop (++i), would i++ be better?
Code:
/* Implement the function int isSorted(unsigned t[], unsigned n)
which checks if the array has the elements in a monotonous order (either increasing or decreasing)returning a logical result; */
#include <stdio.h>
#include <stdlib.h>
void isSorted(unsigned t[], unsigned n){
unsigned counterIncr = 0;
unsigned counterDecr = 0;
for(int i = 0; i < n; ++i){
if(t[i] <= t[i+1])
counterIncr++;
else
if(t[i] > t[i+1])
counterDecr++;
}
if(counterIncr == (n-1))
printf("The array is increasing");
else
if(counterDecr == (n-1))
printf("The array is decreasing");
else
printf("The elements are not sorted");
}
int main()
{
unsigned t[4] = {1, 2, 3, 4};
isSorted(t, 4);
return 0;
}