c - 在 C 中反转数组

标签 c arrays

我正在尝试制作一个程序,该程序接受一个数组并将其向后还原,但是该程序必须以三个为一组对数组执行此操作。因此,如果用户将数字 1、2、3、4、5、6 输入数组,程序将输出:3、2、1、6、5、4。

当我运行当前程序时,我得到:3 2 1 4 5 6。如果有人能帮我弄清楚为什么那会很好,因为我有点困惑。

这是我的代码:

int * numbersProcessFour(int *x, int size) 
{
    int i = 0, three = 3, six = 6, nine = 9;
    if (size < 4) 
    {
        for (i; i < three; i++)
        {
            reverse_array(x, three);
            printf("%d ", x[i]);
        }
    }else if (size > 3 && size < 7) 
    {
        for (i; i < three; i++)
        {
            reverse_array(x, three);
            printf("%d ", x[i]);
        }
        for (i; i < 6; i++)
        {
            reverse_array(x, three);
            printf("%d ", x[i]);
        }
    }
    else if (size > 6 && size < 10) 
    {
        for (i; i < three; i++)
        {
            reverse_array(x, three);
            printf("%d ", x[i]);
        }
        for (i; i < 6; i++)
        {
            reverse_array(x, three);
            printf("%d ", x[i]);
        }
        for (i; i < 9; i++)
        {
            reverse_array(x, three);
            printf("%d ", x[i]);
        }
    }
}
void reverse_array(int *x, int length)
{
    int i, temp;
    for (i = 0; i<length / 2; i++)
    {
        temp = x[i];
        x[i] = x[length - i - 1];
        x[length - i - 1] = temp;
    }
}

最佳答案

从您的评论继续到 flutter 的回答,您可能有点想多了。为了交换数组的每个 3 元素分区中的第 1 个和第 3 个元素,您只需要一次遍历数组 3 个元素。您需要决定如何处理任何最终的部分分区,但由于您的目标是交换第一个和第三个分区,因此在任何小于完整分区的情况下都没有第三个分区,因此合乎逻辑的选择是忽略任何最终的部分分区。

你和 flutter 所做的合并 swap 的变体是:

/* reverse 1st and 3rd element in each group of 3 */
void rev3 (int *a, size_t sz)
{
    if (sz < 3) return;
    size_t i;

    for (i = 0; i < sz; i += 3) {
        if (sz - i < 3) break;
        swap (&a[i], &a[i+2]);
    }
}

你可以把它放在一起:

#include <stdio.h>

void rev3 (int *a, size_t sz);
void swap (int *a, int *b);

int main (void) {

    int a[] = {1,2,3,4,5,6,7,8,9};
    size_t i;

    rev3 (a, sizeof a/sizeof *a);

    for (i = 0; i < sizeof a/sizeof *a; i++) printf (" %2d", a[i]);
    putchar ('\n');

    return 0;
}

void swap (int *a, int *b)
{
    int t = *a;
    *a = *b;
    *b = t;
}

使用示例

编译并运行时,它将为您提供您在问题中指定的整个数组中第一个和第三个元素的交换(反转)。

$ ./bin/revarr3
  3  2  1  6  5  4  9  8  7

无论您使用单独的 swap 还是将该操作包含在您的反转函数中,都没有区别。当过程方法可行时,也不需要招致额外的无意中听到调用递归函数。查看所有答案并比较/对比实现目标的不同方法。

关于c - 在 C 中反转数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36806540/

相关文章:

java - 分解排列的单词列表

c++ - C/C++中数组中最小值的地址

c++ - 有没有模拟器编程教程或指南?

MS-DOS 的 C 编译器

c - 当不确定它是 int 还是 char 时如何从 stdin 中获取值?

c++ - 如何在 C(首选)/C++ 中按顺序将一组一维数组传递给函数

jQuery 从数组中旋转类

c - 符号扩展 C 中的九位数字

c - 我的代码中的垃圾结果

ios - 如何搜索字典数组并在 UITableview 中显示?