P
pereges
I've an array :
{100,20, -45 -345, -2 120, 64, 99, 20, 15, 0, 1, 25}
I want to split it into two different arrays such that every number <=
50 goes into left array and every number > 50 goes into right array.
I've done some coding but I feel this code is very inefficient:
void split_array(int *a, int size_of_array)
{
/* a is the pointer to the array which is going to be partitioned */
int i, left_size =0, right_size = 0;
int *b, *c /* pointers to new arrays */
for(i =0; i< size_of_array; i++)
{
if(a <= 50)
left_size++;
if(a > 50)
right_size++;
}
b = calloc(sizeof(*b) * left_size);
c = calloc(sizeof(*c) * right_size);
if( b == NULL || c == NULL)
{
fprintf(stderr, "memory allocation failure: %s %d %s", __FILE__,
__LINE__, __func__);
exit(EXIT_FAILURE);
}
left_size = right_size = 0;
for(i =0; i< size_of_array; i++)
{
if(a <= 50)
b[left_size] = a;
if(a > 50)
c[right_size] = a;
}
exit(EXIT_SUCCESS);
}
I'm really not comfortable with running similar for loops two times.
Is this bad programming ?
{100,20, -45 -345, -2 120, 64, 99, 20, 15, 0, 1, 25}
I want to split it into two different arrays such that every number <=
50 goes into left array and every number > 50 goes into right array.
I've done some coding but I feel this code is very inefficient:
void split_array(int *a, int size_of_array)
{
/* a is the pointer to the array which is going to be partitioned */
int i, left_size =0, right_size = 0;
int *b, *c /* pointers to new arrays */
for(i =0; i< size_of_array; i++)
{
if(a <= 50)
left_size++;
if(a > 50)
right_size++;
}
b = calloc(sizeof(*b) * left_size);
c = calloc(sizeof(*c) * right_size);
if( b == NULL || c == NULL)
{
fprintf(stderr, "memory allocation failure: %s %d %s", __FILE__,
__LINE__, __func__);
exit(EXIT_FAILURE);
}
left_size = right_size = 0;
for(i =0; i< size_of_array; i++)
{
if(a <= 50)
b[left_size] = a;
if(a > 50)
c[right_size] = a;
}
exit(EXIT_SUCCESS);
}
I'm really not comfortable with running similar for loops two times.
Is this bad programming ?