The task was to write quicksort for an unknown type of elements in an array (using only C code), but my code does not work for the last two elements. The output of the following numbers: '67 45 44 33 5 1 -3 0 -4 -100 'I also tried to debug, but the only thing I understood was that the last digits were simply not compared.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <memory.h>
typedef int typeEl;
void swap(void* a, void* b, size_t sizeOfElem) {
void* tmp = calloc(1,sizeOfElem);
memcpy(tmp, a, sizeOfElem);
memcpy(a, b, sizeOfElem);
memcpy(b, tmp, sizeOfElem);
}
int compare(const void* a, const void* b)
{
return (*(typeEl*)a - *(typeEl*)b);
}
void quickSortR(void* a, long N, size_t sizeOfElem, int (*comp)(const void* c, const void* d))
{
long i = 0, j = N;
void* p = (void *) ((char *)a + (N>>1)*sizeOfElem);
do {
while ( comp((void *) ((char *)a + i*sizeOfElem), p)>0) i++;
while ( comp((void *) ((char *)a + j*sizeOfElem), p)<0) j--;
if (i <= j) {
swap((void *) ((char *)a + i*sizeOfElem), (void *) ((char *)a + j*sizeOfElem), sizeOfElem);
i++; j--;
}
} while ( i<=j );
if ( j > 0 ) quickSortR((void *)a, j, sizeOfElem, comp);
if ( N > i ) quickSortR((void *) ((char *)a + i*sizeOfElem), N-i,sizeOfElem, comp);
}
int main() {
int n;
int m[10] = {1,-3,5,-100,45,33,44,67,-4, 0};
quickSortR((void *)m, 10, sizeof(int),compare);
for (n=0; n<10; n++)
printf ("%d ",m[n]);
return 0;
}
Can anyone advise? thanks for the help!