<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>