剑指offer 14---调整数组顺序使奇数位于偶数前面

时间:2022-09-03 10:32:01

题目:

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。


解析:

剑指offer 14---调整数组顺序使奇数位于偶数前面

#include <iostream>
#include <assert.h>
#include <Windows.h>
using namespace std;

//整数数组中,奇数位于偶数前面
void OddEvenNumber(int* arr, int length)
{
if (arr == NULL || length == 0)
{
return;
}
int* begin = arr;
int* end = arr + length - 1;
while (begin < end)
{
//判断一个数是偶数还是奇数,也可以用 x&1
while ((begin<end) && (*begin) % 2 == 1) //此时为奇数
{
++begin;
}
while ((begin<end) && (*end) % 2 == 0) //此时为偶数
{
--end;
}
while ((begin<end) && ((*begin) % 2 == 0) && ((*end) % 2 == 1))
{
*begin = *begin^*end;
*end = *begin^*end;
*begin = *begin^*end;
++begin;
--end;
}
}
}

void Test()
{
int arr[] = { 1, 3, 3, 4, 5, 6, 9, 8, 9, 10, 11, 34, 5, 6, 89, 0, 12 };
int length = sizeof(arr) / sizeof(arr[0]);
OddEvenNumber(arr, length);
int i = 0;
for (; i < length; ++i)
{
cout << arr[i] << " ";
}
cout << endl;
}

int main()
{
Test();
system("pause");
return 0;
}

剑指offer 14---调整数组顺序使奇数位于偶数前面


扩展:

1.如果将题目改为把数组中的数按照大小分为两部分,所有负数都位于非负数的前面,怎么做?

PS:这个题目几乎和上述题目相同,只需要改几个条件

//整数数组中,所有负数位于非负数前面
void OddEvenNumber(int* arr, int length)
{
if (arr == NULL || length == 0)
{
return;
}
int* begin = arr;
int* end = arr + length - 1;
while (begin < end)
{
//所有负数位于非负数前面
while ((begin<end) && ((*begin)<0)) //此时为负数
{
++begin;
}
while ((begin<end) && ((*end)>=0)) //此时为非负数
{
--end;
}
//此时begin指向非负数,end指向负数,需要交换
while ((begin<end) && ((*begin) >=0) && ((*end)<0))
{
*begin = *begin^*end;
*end = *begin^*end;
*begin = *begin^*end;
++begin;
--end;
}
}
}


2.如果在将题目改为,能被3整除的数都放在不能被3整除的前面,怎么办?

PS:  还是只需要改几个判断条件。可以将不同的部分封装成不同的函数,在函数体里调用完成不同功能。