以阵列交换元件 [英] Swapping element in an array
问题描述
我一直在努力工作,这一点:
I've been trying to work this out:
说我有一个数组:
int[] n = {0, 0, -1, 1, 0, 1, 1, -1, 1};
我需要能够通过数组进行排序,如果有一个非零preceding它一个零,那么就应该被交换。
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.
例如: 0,0,-1,1,0,1,1,-1,1
将成为: 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?
推荐答案
试试这个:
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;
}
您正确的思维,你需要在它的身上带有 A
语句当中。所有我们在这里所做的是通过数组循环开始元素1.然后,我们检查,如果我们目前的元素是为
循环,如果 0
的和的在previous元素不是 0
:即如果(N [I] == 0安培;&安培; N [I - 1]! = 0)
。如果这种情况是真的,我们交换这两个元素。
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.
这篇关于以阵列交换元件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!