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 2595
醉梦人生
醉梦人生 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条回答
  •  旧时难觅i
    2020-12-07 08:33

    I hope this helps. This one has Time Complexity O(n^2)

    #include 
    
    int main() {
        int a[] = {-3, 2, -5, 9, -2, -8, 6, 8, -1, 6};
    
        int length = (sizeof(a) / sizeof(int));
        int i, j = 0;
    
        printf("Size of array: %d\n", sizeof(a));
    
        for (i = 0; i < length; i++) {
            if (i % 2 == 0 && a[i] < 0) {
                for (j = i + 1; j < length; j++) {
                    if (a[j] > 0) {
                        int t = a[i];
                        a[i] = a[j];
                        a[j] = t;
                        break;
                    }
                }
            } else if (i % 2 == 1 && a[i] > 0) {
                for (j = i + 1; j < length; j++) {
                    if (a[j] < 0) {
                        int t = a[i];
                        a[i] = a[j];
                        a[j] = t;
                        break;
                    }
                }
            }
        }
    
        for (i = 0; i < length; i++) {
            printf("Value at %d: %d\n", i, a[i]);
        }
    
        return 0;
    }
    

    EDIT 1 This relies on the fact that numbers greater than zero are always at an even index and numbers less than zero are always at odd index

    EDIT 2 Improved the code a little

提交回复
热议问题