1. 程式人生 > >C#調整數組順序,讓奇數位於偶數前面的算法的代碼

C#調整數組順序,讓奇數位於偶數前面的算法的代碼

new t rgs temp while ole ogr list lin print

寫內容之余,把寫內容過程中比較重要的內容記錄起來,如下的資料是關於C#調整數組順序,讓奇數位於偶數前面的算法的內容,希望對碼農們有用。

#region 調整數組順序使奇數位於偶數前面
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();  

}  

}

C#調整數組順序,讓奇數位於偶數前面的算法的代碼