Swapping element in an array

76,947

Solution 1

Try this:

for (int i = 1 ; i < n.length ; i++)
    if (n[i] == 0 && n[i - 1] != 0) {
        int tmp = n[i - 1];
        n[i - 1] = n[i];
        n[i] = tmp;
    }

You were right in thinking that you would need a for loop with an if statement in its body. All we're doing here is looping through the array starting at element 1. We then check if the element we're currently on is 0 and the previous element is not 0: i.e. if (n[i] == 0 && n[i - 1] != 0). If this condition is true, we swap these two elements.

Solution 2

for(int i=0; i < length; i++)
{
    if(i > 0 && arr[i] == 0 && arr[i-1] != 0)
    {
        int temp = arr[i-1];
        arr[i-1] = arr[i];
        arr[i] = temp;
    }
}

Should work.

Share:
76,947
Nicholas
Author by

Nicholas

Updated on August 22, 2020

Comments

  • Nicholas
    Nicholas over 3 years

    I've been trying to work this out:

    Say I have an array:

    int[] n = {0, 0, -1, 1, 0, 1, 1, -1, 1};
    

    I need to be able to sort through the array and if there is a zero with a non zero preceding it, then they should be swapped.

    For example: 0, 0, -1, 1, 0, 1, 1, -1, 1

    will become: 0, 0, -1, 0, 1, 1, 1, -1, 1

    I have been trying to do it using a for loop and if statements with no luck. Any tips?

  • jli
    jli over 11 years
    To the downvoter: I understand why you did this. However, I did not post a full solution, I just posted a simple example of how two variables are often swapped, with a suggestion of how to use a similar technique.
  • Steven Mastandrea
    Steven Mastandrea over 11 years
    Why not start your for loop at i=1, since your if clause has i > 0 in the check?
  • arshajii
    arshajii over 11 years
    I don't see the issue with even posting the full solution as long as it coupled with some explanation. Read this (specifically the comments).
  • Lews Therin
    Lews Therin over 11 years
    True, I could do that. Yet it doesn't render the algorithm incorrect.
  • arshajii
    arshajii over 11 years
    I quote Tim Post: "If you don't want a fully vetted, complete and testable answer, Stack Overflow is not the place to ask."
  • arshajii
    arshajii over 11 years
    Yes I know - I was just speaking in general because you mentioned "I did not post a full solution" indicating that doing so would be reason for a downvote.