push all the non zero elements

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Merin Lalu
    New Member
    • Oct 2011
    • 20

    push all the non zero elements

    Can any one tell me how to push all the non zero elements to one end of an array in java without creating a new array.
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    If you really don't want to create a new array then use bubble sort.

    Better remove that restriction and use an OO approach like

    Code:
    static class NullComparator<T extends Number> implements Comparator<T> {
    	@Override
    	public int compare(T o1, T o2) {
    	    if (o1 == null || o1.intValue() == 0) {
    		return -1;
    	    }
    
    	    return 1;
    	}
        }
        public static void main(String[] args) {
    	Long[] arrayToSort = new Long[] { null, 42l, null, 0l, 24l, 0l, 42l };
    	Arrays.sort(arrayToSort, new NullComparator());
    	System.out.println(Arrays.toString(arrayToSort));
        }

    Comment

    • Merin Lalu
      New Member
      • Oct 2011
      • 20

      #3
      i got it.. thank you for your reply..

      Comment

      Working...