Results 1 to 2 of 2
Thread: Array help :(
- 11-28-2010, 03:50 PM #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 :)
- 11-28-2010, 04:15 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 14,422
- Blog Entries
- 7
- Rep Power
- 29
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; } }
JosBuild a wall around Donald Trump; I'll pay for it.
Similar Threads
-
convert byte array into char array
By kgkamaraj in forum New To JavaReplies: 4Last Post: 09-13-2011, 12:32 PM -
Variable of an object in an array compared to an element of another array?
By asmodean in forum New To JavaReplies: 23Last Post: 09-07-2010, 09:12 PM -
Trying to make an array list // inserting an element to middle of array
By javanew in forum New To JavaReplies: 2Last Post: 09-06-2010, 02:03 AM -
create a 2d char array from a 1D string array
By jschmall12 in forum New To JavaReplies: 1Last Post: 04-27-2010, 10:01 PM -
How to add an integer to a array element and the store that backinto an array.
By Hannguoi in forum New To JavaReplies: 1Last Post: 03-31-2009, 07:40 AM
Bookmarks