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 2362
醉梦人生
醉梦人生 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:19

    O(n) solution Java

        private static void rearrange(int[] arr) {
        int pos=0,end_pos=-1;
        for (int i=0;i<=arr.length-1;i++){  
            end_pos=i;
            if (arr[i] <=0){
                int temp_ptr=end_pos-1;
                while(end_pos>pos){
                    int temp = arr[end_pos];
                    arr[end_pos]=arr[temp_ptr];
                    arr[temp_ptr]=temp;
                    end_pos--;
                    temp_ptr--;
                }
                pos++;
            }
    
        }
    

提交回复
热议问题