写内容之余,把写内容过程中比较重要的内容记录起来,如下的资料是关于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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。