So I have this problem. I am supposed to create some ordering functions to be used in a generic sort routine in C. I have all but one function working. This function is supposed to be used as an ordering function for structures. The code should put the list in order by year.
Here is code for two helper functions that have been pre-written and used for the sorting routine:
static
void swap(void **left, void **right) {
void *temp = *left;
*left = *right;
*right = temp;
}
void sort_array(void *Array[], unsigned size, int (*ordered)(void *, void *))
{
int i;
int have_swapped = 1;
while (have_swapped) {
have_swapped = 0;
for (i = 0; i < size - 1; ++i ){
if (ordered(Array[i], Array[i+1])) {
swap(&Array[i], &Array[i+1]);
have_swapped = 1;
}
}
}
}
Then there is this function, also pre-written used in main to test.
int main() {
int i;
int status = EXIT_SUCCESS;
sort_array((void**)data, data_size, &ordered_structures);
for (i = 0; i < data_size - 1; ++i) {
if (data[i]->year > data[i+1]->year) {
fprintf(stderr,
"\"%s\" and \"%s\" are out of order\n",
data[i]->name,
data[i+1]->name);
status = EXIT_FAILURE;
}
}
return status;
}
The structure is simple.
struct automobile {
const char *name;
unsigned year;
unsigned price;
};
So these are the helper functions that are used. All I have to do is to write a function that will be used in ordering structures using these helper functions.
My solution compiles, however it is not achieving the desired results, my solution is still out of order. Here is what I have.
int ordered_structures(void *left, void *right) {
const int *x = left;
const int *y = right;
if (x < y)
return 0;
else
return 1;
}
Any help is greatly appreciated