By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,651 Members | 1,316 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,651 IT Pros & Developers. It's quick & easy.

push all the non zero elements

P: 20
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.
Mar 8 '12 #1
Share this Question
Share on Google+
2 Replies


10K+
P: 13,264
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

Expand|Select|Wrap|Line Numbers
  1. static class NullComparator<T extends Number> implements Comparator<T> {
  2.     @Override
  3.     public int compare(T o1, T o2) {
  4.         if (o1 == null || o1.intValue() == 0) {
  5.         return -1;
  6.         }
  7.  
  8.         return 1;
  9.     }
  10.     }
  11.     public static void main(String[] args) {
  12.     Long[] arrayToSort = new Long[] { null, 42l, null, 0l, 24l, 0l, 42l };
  13.     Arrays.sort(arrayToSort, new NullComparator());
  14.     System.out.println(Arrays.toString(arrayToSort));
  15.     }
  16.  
Mar 8 '12 #2

P: 20
i got it.. thank you for your reply..
Mar 8 '12 #3

Post your reply

Sign in to post your reply or Sign up for a free account.