题目:设计一个将整数数组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
{
;
}
}
}