简体   繁体   English

在数组中交换奇数和偶数,C

[英]swap odd and even numbers inside an Array, C

Input array is for example Array[10] = {12,23,0,-7,138,22,7,99,10,-2}输入数组例如 Array[10] = {12,23,0,-7,138,22,7,99,10,-2​​}

I want to print out the array with even numbers on one end and odd numbers on the other, something like this: Array[10] = {12,0,-2,10,22,138,-7,99,7,23}我想打印出一端为偶数而另一端为奇数的数组,如下所示: Array[10] = {12,0,-2,10,22,138,-7,99,7,23}

int main()
{
    int N = 0, i = 0, j = N-1, index = 0;
    printf("Enter N (0>N<10): ");
    scanf("%d", &N);

    int Array[N];
    for(i=0;i<N;i++){
        printf("Enter the value number %d :", i+1);
        scanf("%d", &Array[i]);
    }
    printf("Array[%d] ={",N);
    for(i=0;i<N;i++){
        printf("%d\t", Array[i]);
    }
    printf("}");

    // swaping odd and even numbers

    int Array2[N];
    while (i < j){
        if(Array[i]%2 == 0){
            Array2[i] = Array[index];
            i++;
        }
        else{
            Array2[j] = Array[index];
            j++;
        }
        index++;
    }

    // view the new array

    printf("\n Array[%d] ={",N);
    for(i=0;i<N;i++){
        printf("%d\t", Array2[i]);
    }
    printf("}");

    return 0;
}

This doesn't seem to work.这似乎不起作用。 Any help would be appreciated.任何帮助,将不胜感激。

Note: I know the Array[N] part is not how it's supposed to be done, it's just to simplify things.注意:我知道 Array[N] 部分不是它应该如何完成的,它只是为了简化事情。

Here's an idea I just came up with.这是我刚刚想到的一个想法。 I haven't tested it, that's up to you (this is just pseudo-code).我还没有测试过,这取决于你(这只是伪代码)。

array[n] = {...}
newarray[n]
i = 0
j = n-1
index = 0
while (i < j){
    if (array[index] is even)
        newarray[i] = array[index]
        i = i + 1
    else
        newarray[j] = array[index]
        j = j -1
    index = index + 1
}

This is analogous to the Partition section of Quicksort, except instead of dividing elements by comparing them to a pivot, you use their even/odd-ness.这类似于 Quicksort 的 Partition 部分,不同之处在于不是通过将元素与主元进行比较来划分元素,而是使用它们的偶数/奇数。 One benefit is not needing a second "scratch" array.一个好处是不需要第二个“临时”阵列。 (Your example did not seem to care about the order of either side, just the proper partitioning.) (您的示例似乎并不关心任何一方的顺序,只关心正确的分区。)

int i = 0;
int j = n-1;
while ( i < j ) {
    // Invariant: Array[0..i-1] are even and Array[j+1..n-1] are odd
    while ( Array[i] % 2 == 0 ) // Array[0..i] is even
        i++;
    while ( Array[j] % 2 == 1 ) // Array[j..n-1] is odd
        j--;
    if ( i < j ) { // Array[j] and Array[i] are in the wrong sides
        // Swap them into the correct sides
        int temp = Array[i];
        Array[i] = Array[j];
        Array[j] = temp;
        // Now we can extend each correct side
        i++;
        j--;
    }
}

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

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