Sunday, March 16, 2014

Program to shift all zeros in an integer array to the end

1:  package com.mridul.java.dump;  
2:  import java.io.BufferedReader;  
3:  import java.io.InputStreamReader;  
4:  /**  
5:   * Program to all sort zeros to end of an  
6:   * integer array. The algorithm is O(n)  
7:   * @author Mridul J Kurup  
8:   * @date 03/17/2014  
9:   *   
10:   */  
11:  public class NumSort{  
12:       static int len=0;  
13:       static int data[];  
14:       /*  
15:        * Private static method to sort the array  
16:        * with all zeros transposed to the end  
17:        */  
18:       private static void sortArray(String input){  
19:            data=new int[len];  
20:            int numOfZeroes=0;  
21:            //store all non zero digits  
22:            System.out.println("The re-arranged numbers are : ");  
23:            for(int index=0;index<len;index++){  
24:                 int currDigit=Integer.parseInt(String.valueOf  
25:                           (input.charAt(index)));  
26:                 //skip if zero is encountered   
27:                 if(currDigit==0){  
28:                      ++numOfZeroes;  
29:                      continue;  
30:                 }else{  
31:                      //add rest of the digits to array   
32:                      data[index]=currDigit;  
33:                      System.out.print(data[index]);  
34:                 }  
35:            }  
36:            //attach all zeros to end  
37:            for(int index=(len-numOfZeroes-1);index<len;index++){  
38:                 data[index]=0;  
39:                 System.out.print(data[index]);  
40:            }  
41:            //new line  
42:            System.out.println();  
43:       }  
44:       /*  
45:        * program start point  
46:        */  
47:       public static void main(String... args) {  
48:            try{            
49:                 System.out.println("Enter the int array including zeros");  
50:                 BufferedReader bsr=new BufferedReader(  
51:                           new InputStreamReader(System.in));  
52:                 String input=bsr.readLine();  
53:                 System.out.println("The input is "+input);  
54:                 len=input.length();                 
55:                 //test for length  
56:                 if(len>0){  
57:                      sortArray(input);  
58:                 }else{  
59:                      System.out.println("Please enter valid int array");  
60:                 }  
61:            }catch(Throwable t){  
62:                 t.printStackTrace();  
63:            }  
64:       }  
65:  //End of NumSort.java       
66:  }  

No comments:

Post a Comment