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.
push all the non zero elements
Collapse
X
-
Tags: None
-
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