"lancer6238" <[EMAIL PROTECTED]> wrote:
>
> Hi,
> I'm writing a program that separates a set of integers into
> groups and then quicksort each group individually. However,
> I'm having problems with my realloc() function.

You're over complicating things.

> #include <stdio.h>
> #include <stdlib.h>
> #include <time.h>
> 
> #define N 10            // number of integers to sort
> #define size 2          // number of groups

It's generally best to be consistent. If your other
constants are upper case, make this one upper case.
That said, there are obvious better names, like say
GROUPS.

> #define MAX 100      // maximum value of the integers
> 
> void quicksort(int a[], int lo, int hi) 
<snip>
> 
> int main()
> {
>    int i, j, *length, x[N], **a, *temp;
>    srand(time(NULL));
> 
>    a = (int **)malloc(size * sizeof(int*));

  a = malloc(size * sizeof *a);

You should also check the return value, as you did with
realloc.

>    for (i = 0 ; i < size ; i++)
>       a[i] = (int*)malloc((N/size + 1) * sizeof(int));

You don't need to pre-allocate. But not how many a[]
elements you allocate. [Compare with how many you free.]

> 
>    length = (int *)malloc(size * sizeof(int));

You create memory, but you never initialise its contents.

  for (i = 0; i < size; i++)
    length[i] = 0;

>    /* Generate random integers */
>    printf("Original: \n");
>    for (i = 0 ; i < N ; i++)
>    {
>       x[i] = rand() % MAX;
>       printf("%d ", x[i]);
>    }
>    printf("\n\n");
> 
>    for (j = 0 ; j < N ; j++)
>    {
>       for (i = size ; i >= 1 ; i--)

  for (i = size; --i > 0; )

That saves you having to write (i-1) all over the place
below.

>       {
>               if ((double)x[j]/(double)MAX > (double)(i-1)/(double)
size)
>          {
>             a[i-1][length[i-1]] = x[j];
>             length[i-1]++;
>             if (length[i-1] > N/size + 1)
>             {
>               if ((temp = realloc(a[i-1], sizeof(int) * 2 * (N/size 
+ 1)))
> == NULL)
>               {
>                   printf("ERROR: realloc failed");
>                   exit(0);
>               }
>               a[i-1] = temp;
>             }
>             break;
>          }
>       }
>    }

  for (j = 0; j < N; j++)
  {
    i = (long) x[j] * size / MAX;

    temp = realloc(a[i], (length[i] + 1) * sizeof *a[i]);
    if (!temp) { exit(0); }
    a[i] = temp;

    a[i][length[i]++] = x[j];
  }

>    for(i = 0 ; i < size ; i++)
>       quicksort(a[i],0,length[i]-1);
> 
>    printf("Sorted:\n");
>    for(i = 0 ; i < size ; i++)
>    {
>       for (j = 0 ; j < length[i] ; j++)
>          printf("%d ", a[i][j]);
>    }
>    printf("\n");                                                 
> 
>    for (i = 0 ; i < length[i] ; i++)
>       free(a[i]);

You allocated 'size' elements to a, not length[i].

>    free(a);
>    free(length);
>    return 0;
> }

-- 
Peter

Reply via email to