C#调整数组顺序,让奇数位于偶数前面的算法
转自:http://blog.csdn.net/ywjun0919/
#region 调整数组顺序使奇数位于偶数前面 /// <summary> /// 输入一个 整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分 /// Reorder中array为待排序的数组,使用组合的方式调用使用何种方法进行排序(如奇数在前,偶数在后,或能被3整除的数在前,不能被3整除的数在后) /// </summary> class Reorder { private List<int> _array; private RecorderOperator _op; public List<int> array { get { return _array; } set { _array = value; } } public RecorderOperator op { get { return _op; } set { _op = value; } } public Reorder(List<int> array, RecorderOperator op) { _array = array; _op = op; } public Reorder() { } public void ReorderArray() { int length = array.Count; int start = 0, end = length - 1; while (start < end) { while (start < end && !op.Operator(array[start])) start++; while (start < end && op.Operator(array[end])) end--; if (start < end) { int temp = array[start]; array[start] = array[end]; array[end] = temp; } } } public void Print() { array.ForEach(a=>Console.Write(a+" ")); Console.WriteLine(); } } class RecorderOperator { public virtual bool Operator(int n) { return false; } } class ConcreteRecorderOperator1:RecorderOperator { public override bool Operator(int n) { return (n & 0x1)==0; } } class ConcreteRecorderOperator2 : RecorderOperator { public override bool Operator(int n) { return n%3!=0; } } #endregion class Test{ public void ReorderTest() { RecorderOperator op1 = new ConcreteRecorderOperator1(); Reorder reorder = new Reorder(new List<int>{2,3,4,9,5},op1); Console.WriteLine("所有奇数位于数组的前半部分,所有偶数位于数组的后半部分"); reorder.Print(); reorder.ReorderArray(); reorder.Print(); RecorderOperator op2 = new ConcreteRecorderOperator2(); reorder.op = op2; reorder.ReorderArray(); Console.WriteLine("能被3整除的数在前,不能被3整除的数在后"); reorder.Print(); } } class Program { static void Main(string[] args) { Test t = new Test(); t.ReorderTest(); } }