在一个特定的顺序Aranging整数 [英] Aranging integers in a specific order

查看:115
本文介绍了在一个特定的顺序Aranging整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于S1,S2,...,SN你怎么安排整数,使得S1℃的设定不同的未分类的整数; S2> S3< S4 ...

Given a set of distinct unsorted integers s1, s2, .., sn how do you arrange integers such that s1 < s2 > s3 < s4...

我知道这可以通过查看该阵列从左至右,并且如果条件未被满足交换这两个元件给出正确的答案来解决。有人可以解释我为什么这个算法的工作。

I know this can be solved by looking at the array from left to right and if the condition is not satisfied swapping those two elements gives the right answer. Can someone explain me why this algorithm works.

推荐答案

由于任何三个连续数字数组中,有四种可能的关系:

Given any three successive numbers in the array, there are four possible relationships:

a < b < c
a < b > c
a > b < c
a > b > c

在第一种情况下,我们知道,一个&LT; C。由于第一条件得到满足,就可以交换b和c满足第二条件,和第一条件仍然满足。

In the first case we know that a < c. Since the first condition is met, we can swap b and c to meet the second condition, and the first condition is still met.

在第二种情况下,两个条件都已经满足。

In the second case, both conditions are already met.

在第三种情况下,我们必须交换a和b给B&LT;一个 ? C。但是,我们已经知道,B&LT; C,所以如果&LT; C,那么交换,以满足第二个条件不第一个条件无效。

In the third case, we have to swap a and b to give b < a ? c. But we already know that b < c, so if a < c then swapping to meet that second condition doesn't invalidate the first condition.

在过去的情况下,我们知道A> C,所以交换a和b,以满足第一个条件保持的第二个条件的有效性。

In the last case we know that a > c, so swapping a and b to meet the first condition maintains the validity of the second condition.

现在,您添加第四个号码的顺序。你有:

Now, you add a fourth number to the sequence. You have:

a < b > c ? d

如果C&LT; ð那么就没有必要改变什么。但是,如果我们有交换c和d,在现有条件仍然满足。因为如果B> C和C> D,那么我们就知道B>Ð。所以交换C和D为我们提供了B> D&LT; ℃。

If c < d then there's no need to change anything. But if we have to swap c and d, the prior condition is still met. Because if b > c and c > d, then we know that b > d. So swapping c and d gives us b > d < c.

您可以使用类似的道理,当您添加的第五号。您有 A&LT; B&GT; C&LT; D' Ë。如果D> E,那么就没有必要改变什么。如果D&LT; e,然后根据定义℃下Ë一样,所以交换维持的前提条件。

You can use similar reasoning when you add the fifth number. You have a < b > c < d ? e. If d > e, then there's no need to change anything. If d < e, then by definition c < e as well, so swapping maintains the prior condition.

伪code实现的算法:

Pseudo code that implements the algorithm:

for i = 0 to n-2
    if i is even
        if (a[i] > a[i+1])
            swap(a[i], a[i+1])
        end if
    else
        if (a[i] < a[i+1])
            swap(a[i], a[i+1])
    end

这篇关于在一个特定的顺序Aranging整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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