Given an array of positive and negative integers, re-arrange it so that you have positive integers on one end and negative integers on other

后端 未结 30 2597
醉梦人生
醉梦人生 2020-12-07 07:37

I recently came across a Microsoft Interview Question for Software Engineer.

Given an array of positive and negative integers, re-arrange it so that you

30条回答
  •  难免孤独
    2020-12-07 08:37

    I've tried with the bubble sorting method and it works perfectly and it retain their order of appearance in the original array.

    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);
    
        //MOSTRAR
        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;
                }
            }
        }
    
    }

提交回复
热议问题