以阵列交换元件 [英] Swapping element in an array

查看:125
本文介绍了以阵列交换元件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力工作,这一点:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆