splitting an array.

Discussion in 'C Programming' started by pereges, May 25, 2008.

  1. pereges

    pereges Guest

    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 ?
     
    pereges, May 25, 2008
    #1
    1. Advertising

  2. pereges

    Bartc Guest

    pereges wrote:
    > 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)


    --
    Bartc
     
    Bartc, May 25, 2008
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John Ericson
    Replies:
    0
    Views:
    440
    John Ericson
    Jul 19, 2003
  2. Mark
    Replies:
    0
    Views:
    456
  3. John Dibling
    Replies:
    0
    Views:
    429
    John Dibling
    Jul 19, 2003
  4. Kai Jaensch
    Replies:
    26
    Views:
    728
    Jerry Coffin
    Jan 18, 2004
  5. Kai Jaensch
    Replies:
    3
    Views:
    444
    Kajoka
    Jan 15, 2004
Loading...

Share This Page