An array, put the odd numbers on the left and the even numbers on the right, adjust the ordered method and the unordered method

topic

Such as the title (After writing, I found that even and odd were written backwards... just change the title hhh)

the code

1. Disorder

For convenience, get a printfArray output

void printfArray(int a[])
{
    
    
    int i;
    for (i = 0; i < 10; i++)
    {
    
    
        printf("%d ", a[i]);
    }
    putchar('\n');
}
void disorderSort(int a[])
{
    
    
    int i, j, k;
    for (i = 0, j = 9; i < j; i++, j--) //相遇退出循环
    {
    
    
        while (a[i] % 2) i++; //从左到右找偶数
        while (!(a[j] % 2)) j--; //从右到左找奇数
        k = a[i];
        a[i] = a[j];
        a[j] = k;  //交换
        printfArray(a);
    }
}

Effect:

Find the first even number 86 from left to right, swap with the first odd number 99 from right to left, and so on
insert image description here

2. Orderly

Order means that the relative positions of odd numbers remain unchanged, and the relative positions of even numbers also remain unchanged

void orderSort(int a[])
{
    
    
    int i, j, k, x;
    for (i = 0; ; i++)
    {
    
    
        while (a[i] % 2) i++; //找到从左到右第一个偶数
        j = i + 1;
        while (!(a[j] % 2)) j++; //找到该偶数右边第一个奇数
        if(j > 9) break; //便利完退出循环
        for (x = j; x > i; x--) //向左冒一次泡(大概这个意思)
        {
    
    
            k = a[x];
            a[x] = a[x - 1];
            a[x - 1] = k;
        }
        printfArray(a);
    }
}

Effect

Find the first even number 86 from left to right, then find the first odd number 787 on the right of 86, and bubble;
at this time i = 1, continue, i++;
the same reason;
the more numbers to move to the back;
insert image description here

3. main function

#include <stdio.h>
#include <stdlib.h>
void printfArray(int a[]);
void disorderSort(int a[]);
int main()
{
    
    
    int a[10] = {
    
    47, 86, 787, 87, 4, 79, 8, 98, 99, 2};
    int n;
    printf("原数组为:");
    printfArray(a);
    printf("有序or无序?\n1、有序\n2、无序\n");
    scanf("%d",&n);
    switch(n)
    {
    
    
        case 1: orderSort(a);
                printf("奇偶排序后:");
                printfArray(a);
                break;
        case 2: disorderSort(a);
                printf("奇偶排序后:");
                printfArray(a);
                break;
        default:printf("输入正确编号!\n");
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/LShang2384/article/details/104377547