Arrage number

Question

Given a array containing negative Interger or positive Integer, reorder the array so that negative numbers and positive numbers are separated while keeping the relative order at the same time.

For example:

reorder [3, -10, -2, -5, 10, 4, 5, -1, 10, 2, -4] to [3, 10, 4, 5, 10, 2, -10, -2, -5, -1, -4]

Analysis

Use two pointers

nextPositive representing the next position where to put the positive number

i representing the searching index for the next positive number.

Solution

public void re(int[] num){
  if(num==null || num.length<2) return;
  int nextPositive=0;
  int i=0;
  while(i<num.length){
      if(num[i]>0){
        if(i==nextPositive){
            i++;
            nextPositive++;
        }else{
            int tmp=num[i];
            for(int t=i;t>nextPositive;t--){
            num[t]=num[t-1];
            }
            num[nextPositive++]=tmp;
            i++;
        }
      }else i++;
  }
}

results matching ""

    No results matching ""