Quicksort does not work for the last two numbers

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!

+4
source share
1 answer

There are 3 problems in the code:

  • j = N j = N - 1. : j, , C [0,N-1]

  • p , . , p , - . , , , ( !) :
    :

    void* p = (void *) ((char *)a + (N>>1)*sizeOfElem);
    

    :

    void* p = (void *) ((char *)a + (N>>1)*sizeOfElem);
    void *px = malloc(sizeOfElem);
    memcpy(px, p, sizeOfElem);
    p = px;
    
  • :

    if ( j > 0) quickSortR((void *)a, j, sizeOfElem, comp);
    

    :

    if ( j > 0) quickSortR((void *)a, j + 1, sizeOfElem, comp);
    

    quickSortR .

3 , .

:
3 problems , . , compare ( free(tmp) ). if ( N > i ) if ( N > i + 1 ).
:)

+4

All Articles