简体   繁体   中英

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. How can I make it more efficient?

Exercise: Write a program in which you initialize an array of N elements (N is a constant). 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.

The complexity of most efficient algorithm is 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).

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.

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). Such partitioning is performed recursively on half-sized arrays. The half-sized arrays are then merged by rotating the middle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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