A few things to notice,
- The 'T' parameter wasn't used, so removed.
- The 't' variable wasn't used, so removed.
- The function return type shouldn't be a pointer to integer, it should be just an integer, from your requirements.
- Your code is testing against an array declared in the function scope, and since it is an automatic variable, it is not initialized and may contain garbage values.
- Your code is testing against an out of bounds index when using 'i < len' as the loop condition (ex.: considering that the array length is
3, when i == 2, comparing a[i] with a[i + 1] would access a[3], which is not within array boundaries that goes from index 0 to index 2.
With that in mind, a possible implementation with some tests is provided below, from what I can see from the requirements list, but bear in mind that I made some assumptions, since there was no restriction about them.
#include <assert.h>
#define SORTED_ASC 1
#define SORTED_DES -1
#define UNSORTED 0
int is_sorted(int *arr, int len)
{
int sorted = 0;
// I am assuming that this approach is reasonable, check your requirements.
if (len <= 1)
return UNSORTED;
for (int i = 0; i < len - 1; i++)
{
// Previous iteration detected order as 'descending', but current
// is 'ascending'.
if (sorted == SORTED_DES && arr[i] < arr[i + 1])
return UNSORTED;
// Previous iteration detected order as 'ascending', but current
// is 'descending'.
if (sorted == SORTED_ASC && arr[i] > arr[i + 1])
return UNSORTED;
// I am assuming that arrays with repeated values should remain classified
// as 'unsorted' until a different value appears, check your requirements.
if (arr[i] > arr[i + 1])
sorted = SORTED_DES;
else if (arr[i] < arr[i + 1])
sorted = SORTED_ASC;
}
return sorted;
}
void test_unsorted()
{
int arr[4][3] = {
{ 1, 3, 2 },
{ 2, 1, 3 },
{ 2, 3, 1 },
{ 3, 1, 2 }
};
for (int row = 0 ; row < 4 ; row++)
{
int res = is_sorted(arr[row], 3);
assert(res == UNSORTED);
}
}
void test_sorted_ascending()
{
int arr[] = { 1, 2, 3 };
int res = is_sorted(arr, 3);
assert(res == SORTED_ASC);
}
void test_sorted_descending()
{
int arr[] = { 3, 2, 1 };
int res = is_sorted(arr, 3);
assert(res == SORTED_DES);
}
void test_with_repeated_values()
{
int sorted_asc[] = { 1, 1, 2 };
int sorted_asc_res = is_sorted(sorted_asc, 3);
assert(sorted_asc_res == SORTED_ASC);
int sorted_des[] = { 3, 3, 2 };
int sorted_des_res = is_sorted(sorted_des, 3);
assert(sorted_des_res == SORTED_DES);
int unsorted[] = { 1, 1, 1 };
int unsorted_res = is_sorted(unsorted, 3);
assert(unsorted_res == UNSORTED);
}
int main(void)
{
test_unsorted();
test_sorted_ascending();
test_sorted_descending();
test_with_repeated_values();
}
A[i]>A[i+1]undefined Behaviour wheni== l-1int test(int l, int *T) ...<= remove the star from the return type of the functionsignisintyou want to return pointer to theint(see the star)Ais used not initalized - undefined behaviour