Results 1 to 2 of 2

Thread: Array help :(

  1. #1
    este001 is offline Member
    Join Date
    Nov 2010
    Posts
    1
    Rep Power
    0

    Default 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 :)

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,679
    Blog Entries
    7
    Rep Power
    21

    Default

    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
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. convert byte array into char array
    By kgkamaraj in forum New To Java
    Replies: 4
    Last Post: 09-13-2011, 12:32 PM
  2. Replies: 23
    Last Post: 09-07-2010, 09:12 PM
  3. Replies: 2
    Last Post: 09-06-2010, 02:03 AM
  4. create a 2d char array from a 1D string array
    By jschmall12 in forum New To Java
    Replies: 1
    Last Post: 04-27-2010, 10:01 PM
  5. Replies: 1
    Last Post: 03-31-2009, 07:40 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •