您好,登錄后才能下訂單哦!
寫內容之余,把寫內容過程中比較重要的內容記錄起來,如下的資料是關于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();
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。