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 2604
醉梦人生
醉梦人生 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:36

    This code Work with O(n) complexity and O(1) space. No need to declare another array.

    #include 
    
    int* sort(int arr[], int size)
    {
        int i;
        int countNeg = 0;
        int pos = 0;
        int neg = 0;
    
        for (i = 0; i < size; i++)
        {
            if (arr[i] < 0)
                pos++;
        }
    
        while ((pos < (size-1)) || (neg < size-(pos-1)))
        {
            if ((arr[pos] < 0) && (arr[neg] > 0))
            {
                arr[pos] = arr[pos] + arr[neg];
                arr[neg] = arr[pos] - arr[neg];
                arr[pos] = arr[pos] - arr[neg];
                pos++;
                neg++;
                continue;
            }
            if ((arr[pos] < 0) && (arr[neg] < 0))
            {
                neg++;
                continue;
            }
            if ((arr[pos] > 0) && (arr[neg] > 0))
            {
                pos++;
                continue;
    
            }
            if ((arr[pos] > 0) && (arr[neg] < 0))
            {
                pos++;
                neg++;
                continue;
    
            }
        }
        return arr;
    }
    
    void main()
    {
        int arr[] = { 1, 7, -5, 9, -12, 15 };
        int size = sizeof(arr) / sizeof(arr[0]);
        sort(arr, size);
        int i;
        for (i = 0; i < size; i++)
        {
            printf("%d ,", arr[i]);
        }
        printf(" \n\n");
    }
    

提交回复
热议问题