问题
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?
回答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.
回答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.
回答3:
Without using bit twiddling, you'll need a temporary variable to swap two objects. Example:
int[] n = {...};
int temp = n[3]; // swaps n[3] and n[4]
n[3] = n[4];
n[4] = temp;
You could stick something like this inside your loop to accomplish what you described.
回答4:
public class Swaparray
{
public static void main(String []args)
{
int [] arr={0,1,2,3,4,5,6,7};
Swaparray.displayArray(arr);
for(int i=1;i<arr.length;i++)
{
while(arr[i]%2!=0)
{
int tmp = arr[i - 1];
arr[i - 1] = arr[i];
arr[i] = tmp;
}
}
Swaparray.displayArray(arr);
}
static void displayArray(int[]arr)
{
System.out.print("Array elements are: ");
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i]+" "); }
System.out.println();
}
}
o/p Array elements are: 0 1 2 3 4 5 6 7 Array elements are: 1 0 3 2 5 4 7 6
swapping two consecutive elements in array
回答5:
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int length = arr.length;
int temp;
for (int i = 0; i < length/2; i++)
{
temp = arr[i];
arr[i] = arr[length - i - 1];
arr[length - i - 1] = temp;
}
for (int element:arr)
{
System.out.println (element);
}
来源:https://stackoverflow.com/questions/12653198/swapping-element-in-an-array