Avinash kumar singh
BAN USER{
public class Rearrangingnum {
public Rearrangingnum() {
}
/**
* @param args
*/
public static void main(String[] args)throws IOException {
//Sample input array
int a[]={-10,-20,40,67,6,-3,-22,34,61};
//printing the input array
System.out.println(" \n Intial array is ");
for(int i=0;i<a.length;i++)//order O(n)
System.out.print("\t"+a[i]);
//Declaring tow arrays for getting positive numbers and negative numbers
int pos[]=new int[a.length];
int neg[]=new int[a.length];
int j=0,k=0;
String start="";
//Loop to separate positive and negative numbers
//order is O(n)+O(n)
for(int i=0;i<a.length;i++){
if(a[i]<0 )
{
neg[j]=a[i];
j++;
if(i==0)
start="neg";
}
if(a[i]>0){
pos[k]=a[i];
k++;
if(i==0)
start="pos";
}
}
//Printing the positive and negative arrays
System.out.println(" \n Positive array is ");
for(int i=0;i<pos.length;i++){
System.out.print("\t"+pos[i]);
}
System.out.println(" \n Negative array is ");
for(int i=0;i<neg.length;i++){
System.out.print("\t"+neg[i]);
}
//Merging the positive array and negative array as per given constraints
int l=0,m=0;
for(int i=0;i<a.length-3;i=i+2){
if(start.equals("pos")){
if(l<pos.length)
{a[i]=pos[l];
l++;
}
{if(m<neg.length)
a[i+1]=neg[m];
m++;
}
}
if(start.equals("neg")){
if(l<neg.length)
{a[i]=neg[l];
l++;
}
{if(m<pos.length)
a[i+1]=pos[m];
m++;
}
}
}
System.out.println(" \n Array is \n");
for(int i=0;i<a.length;i++){
System.out.print("\t"+a[i]);
}
}
}
}
{{
- Avinash kumar singh June 25, 2014public class MovingZerosToEnd {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int array[]={1,4,0,0,2,3,0,3,0,0,1};
int finalArray[]=new int[array.length];
int j=0;
for(int i=0;i<array.length;i++){
if(array[i]!=0){
finalArray[j]=array[i];
j++;
}
}
for(int i=0;i<finalArray.length;i++){
System.out.print(finalArray[i]);
}
}
}
}}