Adjust the array so that the odd numbers all come before the even numbers.

Adjust the array so that the odd numbers all come before the even numbers.

Take an array of integers and implement a function to adjust the order of the numbers in the array so that all odd numbers in the array are in the first half of the array and all even numbers are in the second half of the array.

#include<stdio.h>
#include<stdlib.h>
void jiaohuan(int arr[],int i,int j)//交换奇数偶数
{
    int tmp = 0;
    tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
void odd_before(int arr[],int sz)
{
    int left = 0;
    int right = sz-1;//left指向第一个数,right指向最后一个数
    while(left<right)
    {
        while((left<right)&&(arr[left]&0x01))
        {
            left++;
        }//如果下标为left的数为奇数,left向后查找
        while((left<right)&&(!(arr[right]&0x01)))
        {
            right--;
        }//如果下标为right的数为偶数,right向前查找
    jiaohuan(arr,left,right);
    //交换left指向偶数,right指向奇数时的两个数
    }
}
int main()
{
    int arr[] = {1,2,3,4,5,6,7};
    int sz = sizeof(arr)/sizeof(arr[0]);//计算数组长度
    int i = 0;
    odd_before(arr,sz);
    for(i=0;i<sz;i++)
    {
        printf("%d ",arr[i]);
    }
    system("pause");
    return 0;
}

Achieving the result:
write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324663041&siteId=291194637