I am trying to make a qsort type of function that has the same paramenters. I also wrote 3 functions to compare int, float and characters. For some reason it does not work in any case. I don't know whether this is a problem regarded my qsortx function or not, but I checked it several times and it should work perfectly fine. I am not sure what the problem is, or what I am doing wrong. I am currently learning the function pointers and I might not have got everything right related to it. Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void qsortx(void*, int, int, int (*)(const void*, const void*));
int intcmp();
int floatcmp();
int charcmp();
int main()
{
int i,n;
char items[]={'c', 'a', 'b'};
n = 3;
for (i=0;i<n;++i) {
printf("%c ", items[i]);
}
printf("\n");
qsortx(items, n, sizeof(char), charcmp);
for (i=0;i<n;++i) {
printf("%c ", items[i]);
}
printf("\n");
return 0;
}
void qsortx (void *tp, int length, int pace, int(*fp)(const void* a, const void* b)) {
int switched,i,j;
void *p;
p=(void*)malloc(pace);
switched = 1;
while (1) {
if (switched == 0) {
return;
}
switched = 0;
for (i=0; i<length-1;++i) {
for (j=0;j<length-1;++j) {
printf("%c %c", tp+i, tp+j);
if (fp(tp+i, tp+j) > 0) {
memcpy(p, tp+i, pace);
memcpy(tp+i, tp+j, pace);
memcpy(tp+j, p, pace);
switched++;
}
}
}
}
}
int intcmp(const void* a, const void* b) {
return *(int*)a - *(int*)b;
}
int floatcmp(const void* a, const void* b) {
return *(float*)a - *(float*)b;
}
int charcmp(const void* a, const void* b) {
return *(char*)a - *(char*)b;
}
You have multiple problems related to pointer arithmetic and element sizes. You also have a logic error in your sort (which I guess you know is a unidirectional shaker sort). Here's a version of the
qsortx()
function that fixes these deficiencies:Note that:
char *
.pace
) must be taken into account as you step through the input array, else you just scramble your data.switched = 1
is a better choice thanswitched ++
because it cannot overflow, and all you care about is zero vs. non-zero. (Update: butswitched
is no longer relevant.)item1p
loop results in zero swaps. Just because one element is already in its correct place does not mean that all the subsequent elements are also in their correct places. I updated my code above to remove that behavior.free(p)
.bound - pace
in the event that thelength
is zero.