社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
解题思路:
首先设置两个下标,first 和 last,分别指向顺序表第一个和最后一个。然后做出判断:
A[first]
为奇数且A[last]
为偶数,则 first 向后移一位,last 向前移一位。 if (a[first] % 2 == 1 && a[last] % 2 == 0)
{
first++; last--;
continue;
}
A[first]
为偶数,A[last]
为奇数,则先将A[first]
和A[last]
元素进行互换,然后再将 first 向后移一位,last 向前移一位。 if (a[first] % 2 == 0 && a[last] % 2 == 1)
{
int m = a[first];
a[first] = a[last];
a[last] = m;
first++; last--;
continue;
}
A[first]
和A[last]
同为偶数,则保持 first 值不变,last 的值向前移一位。 if (a[first] % 2 == 0 && a[last] % 2 == 0)
{
last--;
continue;
}
A[first]
和A[last]
同为奇数,则保持 last 的值不变,first 的值向后移一位。 if (a[first] % 2 == 1 && a[last] % 2 == 1)
{
first++;
continue;
}
first < last
在这里可以使用while循环
语句实现。在执行完每次判断后要使用continue
语句结束后面的判断,重新从第一个判断开始。完整代码如下:#include<iostream>
using namespace std;
void Get(int A[], int MaxSize)
{
int first(0), last(MaxSize - 1);
while (first < last)
{
if (A[first] % 2 == 1 && A[last] % 2 == 0)
{
first++; last--;
continue;
}
if (A[first] % 2 == 0 && A[last] % 2 == 1)
{
int m = A[first];
A[first] = A[last];
A[last] = m;
first++; last--;
continue;
}
if (A[first] % 2 == 1 && A[last] % 2 == 1)
{
first++;
continue;
}
if (A[first] % 2 == 0 && A[last] % 2 == 0)
{
last--;
continue;
}
}
}
void Print(int a[], int Maxsize)
{
for (int i = 0; i < Maxsize; i++)
{
cout << a[i] << " ";
}
}
int main()
{
int array1[] = { 2,4,6,8,1,3,5,7,9 };
int array1Size = sizeof(array1) / sizeof(int);
Get(array1, array1Size);
Print(array1, array1Size);
}
运行结果:
9 7 5 3 1 8 6 4 2
第一次写CSDN文章,纯属不易,欢迎指出错误。如果各位大佬有更好的方法,欢迎在评论区留言。谢谢~~
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!