1. Member Join Date
Nov 2010
Posts
1
Rep Power
0

## Array help :(

Hello!

I was wondering if it is possible to in an array to move all the elements that have the value zero to the last position in my array, and then print it out.

ex.

1 2 0 4 5
to ->
1 2 4 5 0,

i started to write the code but it didnt seem to work.

for (int x = 0; x < arr.length; x++){

if (arr[x] == 0) {

while (arr[x] < arr[+1] && x < arr.length-1){

int z = 0;
z = arr[x];
arr[x] = arr[x+1];
arr[x+1] = z;
x++;
}

}

System.out.print(arr[x] + " ");
}

is it possible to reposition them using this kind of code?

Any help appriciated :)

And hello every one im new to this site :)  Reply With Quote

2. ## Sure you can do it and you're halfway there already; there's one crucial notion: if you can find a 0 element with a non-0 element to the right of it you're not done yet. This notion "naturally" (mind the quotes) leads to:

Java Code:
```boolean done= false;
while (!done) {
done= true; // assume we're done
for (int i= 0; i < array.length-1; i++)
if (array[i] == 0 && array[i+1] != 0) { // this is the notion
int t= array[i];
array[i]= array[i+1];
array[i+1]= t;
done= false;
}
}```
kind regards,

Jos  Reply With Quote

array 