简体   繁体   English

在数组中配对偶数和奇数

[英]Pairing even and odd numbers in an array

I'm studying for my C exam, and my professor said that my solution to the exercise isn't efficient enough. 我正在为C考试学习,我的教授说我对练习的解决方案不够有效。 How can I make it more efficient? 如何提高效率?

Exercise: Write a program in which you initialize an array of N elements (N is a constant). 练习:编写一个程序,在其中初始化N个元素的数组(N是一个常数)。 In the program, generate and print a new array in which the elements from the first one are ranked according to parity (first even, then odd, they do not have to be in size.) 在程序中,生成并打印一个新数组,其中第一个元素中的元素将根据奇偶校验进行排序(第一个元素是偶数,然后是奇数,它们不必大小)。

My solution was this: 我的解决方案是这样的:

#include <stdio.h> 
#define N 10
int
main ()
{

int a[N] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int b[N];
int i, j, temp;
for (i = 0; i < N - 1; i++)
{
  for (j = i + 1; j < N; j++)
    {
        if (a[j] % 2 == 0)
            {
                temp = a[j];
                a[j] = a[i];
                a[i] = temp;
            }
    }
}

for (i = 0; i < N; i++)
{
  b[i] = a[i];
  printf ("%d,", b[i]);
}

}

Your algorithm is O(N**2) since you have two nested loops that each iterates O(N) times. 您的算法为O(N ** 2),因为您有两个嵌套循环,每个循环都重复O(N)次。

The complexity of most efficient algorithm is O(n). 最有效的算法的复杂度为O(n)。 This is a simple stable partitioning algorithm: 这是一个简单的稳定分区算法:

int write_pos = 0;
/* copy only even: O(N) */
for (int i=0 ; i < N ; i++)
{
  if (a[i] % 2 == 0)
  {
     b[write_pos++] = a[i];
  }
}
/* copy only odd: O(N) */
similar to the above

Total complexity O(N)+O(N) = O(N). 总复杂度O(N)+ O(N)= O(N)。

I am using the additional memory (which was given in the question), but partitioning can also be done in place. 我正在使用额外的内存(在问题中给出了),但是分区也可以就地完成。 In place partitioning runs in O(n), if it is acceptable to have unstable partitioning. 如果可以接受不稳定分区,则在O(n)中进行分区。

If the goal is to have O(1) additional memory and a stable partition (that retains relative order of elements), then runtime complexity becomes O(n log n). 如果目标是增加O(1)个内存和一个稳定的分区(保留元素的相对顺序),则运行时复杂度将变为O(n log n)。 Such partitioning is performed recursively on half-sized arrays. 这种划分是在一半大小的数组上递归执行的。 The half-sized arrays are then merged by rotating the middle. 然后,通过旋转中间尺寸将一半尺寸的阵列合并。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM