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 2586
醉梦人生
醉梦人生 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:40

    This can simply be done by following steps in O(n), without using any extra space

    int count = 0;
    //data is the array/vector in sort container having given input.
    if(data[0] < 0)
        count++;
    for(int i = 1; i < n; i++)
    {
        if(data[i] < 0)
        {
            int j = i;
            while(j> count)
            {
                data[j-1] += data[j];
                data[j] = (data[j-1]-data[j]);
                data[j-1] -= data[j];
                j--;
            }
            count++;
        }
    }
    

    it's complete implementation can be found here https://gist.github.com/Shravan40/8659568

提交回复
热议问题