将一个整型数组奇偶排列

<span style="font-family: Verdana; line-height: 1.5; background-color: rgb(255, 255, 255);">调整数组使奇数全部位于偶数前面</span>
<span style="font-family: Verdana; line-height: 1.5; background-color: rgb(255, 255, 255);"></span><pre name="code" class="cpp">#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>


void change(int arr[], int sz)
{
	int *start = arr;
	int *end = arr + sz - 1;
	while (start < end)
	{
		while (*(start) % 2 != 0)//start找到左端的偶数
		{
			start++;
		}
		while (*(end) % 2 == 0)//end找到右端的奇数
		{
			end--;
		}
		if (start < end)
		{
			int tmp = *start;
			*start = *end;
			*end = tmp;
		}
	}
}
int main()
{
	int arr[] = { 1, 4, 5, 2, 8, 9, 3, 7 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	int i = 0;
	change(arr,sz);
	for (i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
	system("pause");
	return 0;
}


 
  
<span style="font-family:Verdana;"><span style="background-color: rgb(255, 255, 255);">     定义一个整数数组,实现一个函数,来调整该数组中的数字的顺序使得所有的奇数位于数组的前半部分,所有偶数位于数组的后半部分</span></span>
<span style="font-family:Verdana;"><span style="background-color: rgb(255, 255, 255);">     主要思路为:通过传入函数的数组名(首元素地址)和sz(数组长度)定义两个指针指向首尾,头指针向后寻找偶数,尾指针向前寻找奇数,交换两个数,直至两个指针相遇。</span></span>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值