I am finding the order of sorting of an array. The code works but can it be made better especially the return values of the function findSortOrder.
#include <stdio.h>
#include <stdlib.h>
// Returns 0 for unsorted, 1 for sorted in increasing order, 2 for sorted in decreasing order
int findSortOrder(int array[], int len)
{
// holds the sorting order of the subarray array[0...i]
// 0 represents no information about sorting order
// 1 represents sorting in increasing order
// 2 represents sorting in decreasing order
int order = 0;
int i;
for (i = 1; i < len; i++)
{
if (order == 0)
{
if (array[i] > array[i - 1])
{
order = 1;
}
else if (array[i] < array[i - 1])
{
order = 2;
}
}
else if (order == 1)
{
if (array[i] < array[i - 1])
{
return 0;
}
}
else
{
if (array[i] > array[i - 1])
{
return 0;
}
}
}
if (order == 0 || order == 1)
{
return 1;
}
else
{
return 2;
}
}
int main()
{
printf("Enter length of the array: ");
int len;
scanf("%d", &len);
int* input = malloc(len * sizeof(*input));
int i;
for (i = 0; i < len; i++)
{
scanf("%d", &input[i]);
}
int order = findSortOrder(input, len);
switch (order)
{
case 0:
printf("Unsorted\n");
break;
case 1:
printf("Sorted in increasing order\n");
break;
case 2:
printf("Sorted in decreasing order\n");
break;
}
free(input);
return 0;
}
Edit:
I will be using this function to merge two sorted arrays in their sorting order. So I think if no. of elements is 1 or all are equal then sort order could be returned as increasing.