把数组中的所有奇数移动到所有偶数之前

题目:设计一个将整数数组a[0:n-1]中所有奇数移到所有偶数之前的算法。
要求不另外增加存储空间且时间复杂度为O(n)

思路:
1.创建两个指向数组第一个元素的指针front1,front2。
2.用front2使用for循环对数组进行遍历,并判断数组元素的类型(奇数\偶数)
3.如果front2所指向的元素为偶数,则对下一个元素进行奇偶性判断。
4.如果front2所指向的元素为奇数,则将front2所指向的元素与front1所指向的元素进行调换。
5.front2所指向的元素与front1所指向的元素进行调换后,将front1指向下一个元素

main.cpp

#include <iostream>					// 编译预处理命令
using namespace std;				// 使用命名空间std
#include "alg.h"					// 算法
template<class ElemType>
void Show(ElemType elem[], int n)
// 操作结果: 显示数组elem的各数据元素值
{
	for (int i = 0; i < n; i++)
	{	// 显示数组elem
		cout << elem[i] << "  ";
	}
	cout << endl;
}

int main()							// 主函数main()
{

	const int n = 8;				// 元素个数
	int a[n] = { 3, 2, 4, 8, 7, 5, 4, 6 };	// 数组 
	Show(a, n);						// 显示原数组
	Change(a, n);					// 处理数组 
	Show(a, n);						// 显示新数组

	return 0;						// 返回值0, 返回操作系统
}

alg.h

#pragma once
template <class ElemType>
void Change(ElemType a[], int n)
// 操作结果:将整数数组a[0:n-1]中所有奇数移到所有偶数之前的算法。要求不另外增加存储空间且时间复杂度为O(n)
{
	//创建两个指向数组a第一个元素的指针front
	int* front1 = a;
	int* front2 = a;
	int b = 0;
	for (int i = 0; i < n; i++)
	{
		if (front2[i] % 2 == 1)
		{
			int temp;
			temp = front1[b];
			front1[b] = front2[i];
			front2[i] = temp;
				b++;
		}
		else
		{
			;
		}
	}
}
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GT-一二

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值