奇偶分割:
using System;
using System.Collections.Generic;
using System.Text;
namespace NET.MST.Thirteenth.EvenOddPartition
{
partial class EvenOddPartition
{
/// <summary>
/// 测试奇偶分割算法
/// </summary>
static void Main(string[] args)
{
int[] data = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
PrintArray(data);
Partition(data);
PrintArray(data);
Console.Read();
}
/// <summary>
/// 打印数组
/// </summary>
/// <param name="data">整数数组</param>
static void PrintArray(int[] data)
{
Console.Write("数组为:");
for (int i = 0; i < data.Length; i++)
Console.Write("{0},", data[i].ToString());
Console.Write("\r\n");
}
}
partial class EvenOddPartition
{
/// <summary>
/// 分割算法
/// </summary>
/// <param name="data">整数数组</param>
static void Partition(int[] data)
{
if (data.Length <= 1)
return;
//设置上下限
int low = 0;
int high = data.Length - 1;
//设置临时变量
int temp = 0;
//循环直至所有的奇数都在偶数前面
do
{
//循环获取数组中最前面一个偶数
while (!IsEven(data[low]) && low < high)
low++;
//讯后获取数组中最后面一个奇数
while (IsEven(data[high]) && high > low)
high--;
//对换奇数偶数
if (low < high)
{
temp = data[low];
data[low] = data[high];
data[high] = temp;
}
} while (low < high);
}
/// <summary>
/// 判断是否为偶数
/// </summary>
/// <param name="val">整型</param>
/// <returns>返回是否为偶数</returns>
static bool IsEven(int val)
{
if (val % 2 == 0)
return true;
return false;
}
}
}