Saturday, April 26, 2014

In place sort of an array of numbers by zero


Problem:
  Given an array that has positive numbers and negative numbers and zero in it. 
 You need to seperate the negative numbers and positive numbers in such a way that 
 negative numbers lies to left of zero 
  and positive numbers to the right and the original order of elements should be maintained
This essentially is insertion sort algorithm with different comparison criterion. 


public static void orderByZero(int[] num){
for(int i = 1 ; i< num.length; i++){
int j = i ;
while(j>0){
if((num[j]<0 && num[j-1]>=0) || (num[j]==0 && num[j-1]>0)){
int t = num[j];
num[j] = num[j-1];
num[j-1] = t;
j--;
}else{
break;
}
}
}
}

No comments:

Post a Comment