代码改变世界

一个小算法

2011-09-04 00:31  lujiao_cs  阅读(253)  评论(0编辑  收藏  举报

 

要求:将一个整数数组中的奇数和偶数分别放置到数组的前部和后部( 算法复杂度为O(n) )

    /// <summary>   
    /// 将数组中的奇数和偶数分别放置到前部和后部    
    /// </summary>   
    public class OddAndEvenExchange
    {
        /// <summary>        
        /// 待处理的数组       
        /// </summary>        
        public int[] numberLst;

        /// <summary>        
        /// 数组的长度        
        /// </summary>        
        public int Length;
        public OddAndEvenExchange(int[] numberLst)
        {
            if (numberLst == null)
            {
                throw new Exception("数组不能为空!");
            }

            this.numberLst = numberLst;
            Length = numberLst.Length;
        }

        /// <summary>        
        /// 交换算法
        /// 算法复杂度:O(n)
        /// </summary>        
        public void Exchagne()
        {
            if (Length == 0)
            {
                return;
            }

            int headIdx = 0;
            int tailIdx = Length - 1;

            while (headIdx < tailIdx)
            {
                if (numberLst[headIdx] % 2 == 0)
                {
                    if (numberLst[tailIdx] % 2 == 1)
                    {
                        //交换
                        int temp = numberLst[tailIdx];
                        numberLst[tailIdx] = numberLst[headIdx];
                        numberLst[headIdx] = temp;
                    }
                    else
                    {
                        tailIdx--;
                    }
                }
                else
                {
                    headIdx++;
                }
            }
        }

        /// <summary>        
        /// 输出数组信息        
        /// </summary>
        public void OutPut()
        {
            for (int i = 0; i < numberLst.Length; i++)
            {
                Console.WriteLine(numberLst[i]);
            }
        }
    }

 

算法调用:

static void Main(string[] args)
 {
            OddAndEvenExchange test = new OddAndEvenExchange(new int[]{1,2,3,4,5,6,7});
            test.Exchagne();
            test.OutPut();
}

  

输出结果: