1. 程式人生 > >劍指offer面試題14

劍指offer面試題14

面試題14:調整陣列順序使奇數位於偶數前面

題目:輸入一個整數陣列,實現一個函式來調整該陣列中數字的順序,使得所有奇數位於陣列的前半部分,所有偶數位於 

思路:設定兩個指標,一個指標指向陣列的第一個元素,一個指標指向陣列的最後一個元素,然後移動兩個指標,在兩個指標相遇前,第一個指標總是位於第二個指標的前面。如何第一個指標指向的數字是偶數,而且第二指標指向的數字是奇數,那麼就交換著兩個數。

演算法實現:

#include "stdafx.h"

//*****************方法1**********************
void ReorderOddEven_1(int *pData, unsigned int length)
{
	if(pData == NULL || length == 0)
		return;
	int *pBegin = pData;             //指向第一個元素
	int *pEnd = pData + length - 1;  //指向末尾元素
	
	while (pBegin < pEnd) //指標比較
	{
		//pBegin向後移動,直到它指向偶數
		while (pBegin < pEnd && (*pBegin & 0x1) != 0) //*pBegin是奇數的時候,*pBegin & 0x1 等於1
			pBegin ++;

		while (pBegin < pEnd && (*pEnd & 0x1) == 0)  //*pEnd是偶數的時候,*pEnd & 0x1 等於0
			pEnd --;
		
		//交換兩個數
		if (pBegin < pEnd )
		{
			int temp = *pBegin;
			*pBegin = *pEnd;
			*pEnd = temp;
		}
	}
}

//******************方法2**********************
bool isEven(int n)
{
	return (n & 1) == 0;
}
void ReorderOddEven_2(int *pData, unsigned int length, bool (*func)(int))
{
	if (pData == NULL || length == 0)
		return;

	int *pBegin = pData;
	int *pEnd = pData + length -1;

	while ( pBegin < pEnd)
	{
		while (pBegin < pEnd && !func(*pBegin))
			pBegin ++;

		while (pBegin < pEnd && func(*pEnd))
			pEnd --;

		if (pBegin < pEnd )
		{
			int temp = *pBegin;
			*pBegin = *pEnd;
			*pEnd = temp;
		}
	}
}

//========測試程式碼================
void PrintArray(int numbers[], int length)
{
	if (length < 0)
		return;

	for(int i = 0; i < length; ++i)
		printf("%d\t", numbers[i]);

	printf("\n");
}

void Test(char* testName, int numbers[], int length)
{
	if (testName != NULL)
		printf("%s begins:\n", testName);

	int* copy = new int[length];
	for(int i = 0; i < length; ++i)
	{
		copy[i] = numbers[i];
	}

    PrintArray(numbers, length);

	printf("Test for solution 1:\n");	
	ReorderOddEven_1(numbers, length);
	PrintArray(numbers, length);

	printf("Test for solution 2:\n");
	ReorderOddEven_2(copy, length, isEven);
	PrintArray(numbers, length);


	delete [] copy;
}

void Test1()
{
	int numbers[] = {1, 2, 3, 4, 5, 6, 7};
	Test("Test1", numbers, sizeof(numbers)/sizeof(int));
}

int _tmain(int argc, _TCHAR* argv[])
{
	Test1();
	return 0;
}