Marcos MG
Marcos MG

Reputation: 3

Rearrange an array alternating positives & negatives in C

I need to rearrange an array with bubble sorting method so that positive and negatives numbers are alternated but I don't know how to continue it. I've just managed to put all positive numbers at the beginning and the negatives at the end. Any ideas? Thank you very much in advance!

E.g. input= {1,3,-4,5,9,-3,-7} // output= {1,-4,3,-3,5,-7,9}

int main()
{
    int array[TAM], num, i=0, j=0;

    printf("Ingrese arreglo: ");

    for(i=0; i < TAM -1 && num != 0; i++)
    {
        scanf("%d", &num);
        array[i]=num;
    }

    for(i=0; array[i] != 0 ; i++)
    {
        j++;
    }

    Alternar(array, j);

    //print array
    for(i=0; i < j; i++)
    {
        printf("%d ", array[i]);
    }


    return 0;
}

void Alternar(int array[], int j)
{
    int i=0, aux, pasadas=1;

    for(pasadas=1; pasadas < j; pasadas++)
    {
        for(i=0; i < j - pasadas ; i++)
        {
            if((array[i] > 0 && array[i+1] < 0))
            {
                aux = array[i];
                array[i] = array[i+1];
                array[i+1] = aux;
            }
        }
    }
    int aux1=j;

    for(i=0, j; i<aux; i++, j--)
    {
        array[]=array[j];
    }


}

Upvotes: 0

Views: 271

Answers (1)

BLUEPIXY
BLUEPIXY

Reputation: 40145

#include <stdio.h>
#include <string.h>

void Alternar(int array[], int n){//`array` does not include the 0
    int i, j, k, sign;
    sign = (array[0] > 0);//Decide `sign` by the sign of first element.
    for(i = 0; i < n; ++i, sign = !sign){
        if(sign == 1 && array[i] > 0 || sign == 0 && array[i] < 0)
            continue;
        for(j = i + 1; j < n; ++j){
            if(sign == 1 && array[j] > 0 || sign == 0 && array[j] < 0)//find
                break;
        }
        if(j == n)//not find
            break;//return ;
        k = array[j];//save
        memmove(&array[i+1], &array[i], sizeof(int)*(j-i));//shift right
        array[i] = k;//replace
    }
}

int main(void){
    int array[] = {1, 3, -4, 5, 9, -3, -7};
    int i, n = 7;

    Alternar(array, n);

    for(i = 0; i < n; ++i)
        printf("%d ", array[i]);
    puts("");

    return 0;
}

Upvotes: 1

Related Questions