fork(1) download
  1. #include <stdio.h>
  2.  
  3. typedef enum
  4. {
  5. sortUnknown = 0,
  6. sortAscending,
  7. sortDescending,
  8. sortUnsorted
  9. } SortType;
  10.  
  11. const char *sortNames[] =
  12. {
  13. " Unknown",
  14. " Ascending",
  15. "Descending",
  16. " Unsorted",
  17. };
  18.  
  19. SortType is_sorted(int* arr, int size)
  20. {
  21. if (size <= 1)
  22. {
  23. return sortUnknown;
  24. }
  25.  
  26. SortType overallSortType = sortUnknown;
  27. for (int i = 0; i < size - 1; ++i)
  28. {
  29. if (arr[i] < arr[i + 1])
  30. {
  31. if (overallSortType == sortDescending)
  32. {
  33. return sortUnsorted;
  34. }
  35. overallSortType = sortAscending;
  36. }
  37. else if (arr[i] > arr[i + 1])
  38. {
  39. if (overallSortType == sortAscending)
  40. {
  41. return sortUnsorted;
  42. }
  43. overallSortType = sortDescending;
  44. }
  45. }
  46. return overallSortType;
  47. }
  48.  
  49. void print(int *arr, int size, SortType st)
  50. {
  51. printf("%s : ", sortNames[st]);
  52. for (int i = 0; i < size; ++i)
  53. {
  54. printf("%d ", arr[i]);
  55. }
  56. printf("\n");
  57. }
  58.  
  59. int main()
  60. {
  61. int arr1[] = { 1, 1, 2 };
  62. SortType st = is_sorted(arr1, 3);
  63. print(arr1, 3, st);
  64.  
  65. int arr2[] = { 2, 1, -1 };
  66. st = is_sorted(arr2, 3);
  67. print(arr2, 3, st);
  68.  
  69. int arr3[] = { 4, 7, 0, 3 };
  70. st = is_sorted(arr3, 4);
  71. print(arr3, 4, st);
  72.  
  73. int arr4[] = { 3 };
  74. st = is_sorted(arr4, 1);
  75. print(arr4, 1, st);
  76.  
  77. int arr5[] = { 1, 1, 1, 1, 2, 2, 2, 3, 4, 5, 6, 6, 6, 6, 7, 8, 9 };
  78. st = is_sorted(arr5, 17);
  79. print(arr5, 17, st);
  80.  
  81. return 0;
  82. }
  83.  
Success #stdin #stdout 0s 5464KB
stdin
Standard input is empty
stdout
 Ascending : 1 1 2 
Descending : 2 1 -1 
  Unsorted : 4 7 0 3 
   Unknown : 3 
 Ascending : 1 1 1 1 2 2 2 3 4 5 6 6 6 6 7 8 9