splitting an array.

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 ?
 
B

Bartc

pereges said:
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:

This looks like just a sort.

But instead of comparing the element value data, compare (data<50)
instead (so you are effectively comparing lots of 0's and 1's).

I got these results with such a sort:

Before = ( 100, 20, -45, -345, -2, 120, 64, 99, 20, 15, 0, 1, 25)
After = ( 1, -2, 15, 0, 20, 25, -345, -45, 20, 120, 100, 99, 64)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top