已知数组A[n]的元素为整型,设计算法将其调整为两部分,左边所有元素为奇数,右边所有元素为偶数。

解题思路:
首先设置两个下标,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文章,纯属不易,欢迎指出错误。如果各位大佬有更好的方法,欢迎在评论区留言。谢谢~~


版权声明:本文为qq_45974622原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。