C language adjustment: odd numbers are in the first half of the array, and even numbers are in the second half of the array

Input 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 located in the first half of the array, and
    all even numbers are located in the second half of the array

When you see this question, you must first draw a picture and analyze it:

It is much more convenient to write code with the analysis of drawings. The code is shown below:

 

#include<stdio.h>

void print(int * p, int sz)  // 打印函数
{
	int i = 0;
	for (i = 0; i < sz; i++)
	{
		printf("%d ", *(p + i));
	}
}

void diandao(int* p, int r)    // 颠倒函数
{
	int* left = p;
	int* right = p + r;
	while (left < right)
	{
		if (left < right && (*left % 2 == 1)) // 如果左面是单数就向后走
		{
			left++;
		}
		if (left < right && (*right % 2 == 0)) //如果右面是双数就向前走
		{
			right--;
		}
		//下面交换左右的值
		int tmp = *left;
		*left = *right;
		*right = tmp;
	}
}

int main()
{
	int arr[10] = { 1,2,3,4,5,19,7,8,9,10 };
	
	int right = sizeof(arr) / sizeof(arr[0]) - 1;

	diandao(arr, right);  //调用颠倒函数

	print(arr, right);  // 调用打印函数

	return 0;
}

In this way, the function that the odd numbers in the adjustment array occupy the first half and the even numbers occupy the second half is realized.

Guess you like

Origin blog.csdn.net/xingyuncao520025/article/details/131843482