New to C programming ^^.
I am working on an assignment, and I have to create a function that verifies if my array is sorted. I have to use a predefined template of code and solve it in a certain way.
Description :
Let's create a function which will tell us if an array is sorted or not. What is sorted? :-)
Write a function that takes an integer array as a parameter (input) and returns a boolean (true/false).
Your function should return true if the integer array is sorted in either ASC(ascending) or DESC(descending) order. Your function should return false if the integer array is not sorted.
Numbers will be from -2_000_000 to 2_000_000 Array might have duplicate(s).
I have to use this to solve my problem.
#ifndef STRUCT_INTEGER_ARRAY
#define STRUCT_INTEGER_ARRAY
typedef struct s_integer_array
{
int size;
int* array;
} integer_array;
#endif
bool my_is_sort(integer_array* param_1)
{
}
The inputs that will be used to verify my code:
Exemple 0:
Input: [1, 1, 2]
Output:
Return Value: true
Exemple 1:
Input: [2, 1, -1]
Output:
Return Value: true
Exemple 2:
Input: [4, 7, 0, 3]
Output:
Return Value: false
Exemple 3:
Input: []
Output:
Return Value: true
Here is my code :
#include <stdbool.h>
#ifndef STRUCT_INTEGER_ARRAY
#define STRUCT_INTEGER_ARRAY
typedef struct s_integer_array
{
int size;
int* array;
} integer_array;
#endif
bool my_is_sort(integer_array* a)
{
if (a->size == 1 || a-> size == 0)
{
return true;
}
int i;
for (i=0;i<a->size;i++)
{ //ascending order
if (a->array[i] <= a->array[i+1]){
return true;
}else if (a->array[i] >= a->array[i+1]){
return true;
} else {
return false;
}
}
}
The output I get to verify my code : The output failure i get
My mistake is in the input -> Input: [4, 7, 0, 3] My code returns true when it is supposed to return false. It returns true because of the first two indexes 4 is less then 7 so my code assumes that it is in ascending order, but it's not the case I want my code to keep looping to the next one before it returns a boolean. To check if the number after 7 is greater then 7 or not. but I dont know how to do this in code.
Thank you guys!
I know it might be a dumb question for a lot of you, but please help. I am new to this, and I freaking love programming.
This function will check if the array is sorted.
#ifndef STRUCT_INTEGER_ARRAY
#define STRUCT_INTEGER_ARRAY
typedef struct s_integer_array
{
int size;
int* array;
} integer_array;
#endif
typedef enum
{
des,
notdetermined;
asc;
}SORT_TYPE;
bool my_is_sort(integer_array* a)
{
bool result = true;
SORT_TYPE sort = notdetermined;
if (a && a -> array && a -> size > 2)
{
for(int i = 0; i < a -> size - 1 && result; i++)
{
switch(sort)
{
case notdetermined:
if(a -> array[i] > a -> array[i + 1]) sort = des;
else if(a -> array[i] < a -> array[i + 1])) sort = asc;
break;
case asc:
if(a -> array[i] > a -> array[i + 1])) result = false;
break;
case des:
if(a -> array[i] < a -> array[i + 1])) result = false;
break;
}
}
}
return result;
}