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 2520
醉梦人生
醉梦人生 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:20

    An extremely simple solution is below but not in O(n). I changed the insertion sort algorithm a bit. Instead of checking if a number is greater or smaller, it checks if they are greater or less than zero.

     int main() {
    
        int arr[] = {1,-2,3,4,-5,1,-9,2};
    
            int j,temp,size;
    
            size = 8;
            for (int i = 0; i  0)
                while ((j > 0) && (arr[j] >0) && (arr[j-1] < 0)){
                      temp = arr[j];
                      arr[j] = arr[j-1];
                      arr[j-1] = temp;
                      j--;
                }
            }
    
            //Printing
            for(int i=0;i

提交回复
热议问题