Quicksort doesn't work for the last two numbers

Viewed 149

The task was to write quicksort for unknown type of elements in array (using only C code), but my code doesn't work for the last two elements. FOr the following numbers output is '67 45 44 33 5 1 -3 0 -4 -100' I also tried to debug but the only thing I understood is that the last numbers just do not compare.

#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;
}

Anyone can advise? Thx for the help!

1 Answers
Related