/*
题目:输入一个整数数组,实现一个函数来调整数组中数字的顺序。
使得所有奇数数字位于数组的前半部分,所有的偶数在数组的后半部分。
解题思路:
(1):遍历数组。类似于排序。
找到一个偶数,就将偶数放倒最后,然后向前移动数组,复杂度O(n*n),比较缓慢。
(2):类似快速排序的处理方式。前后放置2个指针。
前面指针向后,后面指针向前,如果同时发现奇数和偶数,就交换。
停止条件,后面的指针超越前面的指针。
*/
#include <stdio.h>
//移动数组,从location移动到末尾,而后依次补齐。
void moveArray(int *num, int location, int length)
{
if (num == NULL || location < 0 || length < 0 || location >= length)
return;
int temp = num[location];
for (int i = location; i < length - 1; i++)
{
num[i] = num[i + 1];
}
num[length - 1] = temp;
}
//第一种,循环移动
void firstOrderArray(int *num, int length)
{
if (num == NULL || length <= 1)
return ;
for (int i = 0; i < length; i++)
{
if (0 == num[i]%2)
{
//printf("moveArray -- %d\n", i);
moveArray(num, i, length);
}
}
}
int testNum = 0;
//第二种,快速排序的方式进行交换位置。
void secondOrderArray(int *num, int length)
{
if (num == NULL || length <= 1)
return;
testNum = 0;
int *np_start = num, *np_end = num + length - 1;
while (np_start < np_end)
{
testNum++;
//向后移动np_start,直到它指向偶数
//*np_start & 0x1 != 0 , 证明是
while (np_start < np_end && (*np_start & 0x1) != 0)
np_start++;
while (np_start < np_end && (*np_start & 0x1) == 0)
np_end--;
if (np_start < np_end)
{
int temp = *np_end;
*np_end = *np_start;
*np_start = *np_end;
}
}
printf("testNum === %d\n", testNum);
}
//打印数组
void PrintArray(int *num, int length)
{
for (int i = 0; i < length; i++)
printf("%d \n", num[i]);
printf("\n");
}
//测试1
void testOne(int *num, int length)
{
printf("%d\n", length);
firstOrderArray(num, length);
PrintArray(num, length);
printf ("================\n");
}
//测试2
void testTwo(int *num, int length)
{
//printf("%d\n", length);
secondOrderArray(num, length);
PrintArray(num, length);
printf ("================\n");
}
void testFirst()
{
int num1[] = {1,2,3,4,5,6,7,8,9,10};
int length1 = sizeof(num1)/sizeof(int);
testOne(num1, length1);
int *num2 = NULL;
if (num2 != NULL)
{
int length2 = sizeof(num2)/sizeof(int);
testOne(num2, length1);
}
int num3[] = {7};
int length3 = sizeof(num3)/sizeof(int);
testOne(num3, length3);
}
void testSecond()
{
int num1[] = {1,2,3,4,5,6,7,8,9,10};
int length1 = sizeof(num1)/sizeof(int);
testTwo(num1, length1);
int *num2 = NULL;
if (num2 != NULL)
{
int length2 = sizeof(num2)/sizeof(int);
testTwo(num2, length1);
}
int num3[] = {7};
int length3 = sizeof(num3)/sizeof(int);
testTwo(num3, length3);
}
int main()
{
// testFirst();
testSecond();
return 0;
}