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 2589
醉梦人生
醉梦人生 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:30

    This is not Complexity O(1) but a simpler approach. Do comment

    void divide (int *arr, int len) {
        int positive_entry_seen = 0;                                                                                             
        for (int j = 0; j < len ; j++) { 
            if (arr[j] >= 0 ) { 
                positive_entry_seen = 1;
            } else if ((arr[j] < 0 ) && positive_entry_seen) {
                int t = arr[j];
                int c = j;
                while ((c >= 1) && (arr[c-1] >= 0)) {
                    arr[c] = arr[c-1];
                    c--;
                }   
                arr[c] = t;
            }   
        }   
    }
    

提交回复
热议问题