VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • C#教程之c#冒泡排序示例分享

冒泡排序口诀:

升序(从小到大):两for一if;大于连;相 交换;再来个for遍历;外层N-1;内层N-1-i;

说再多不如上代码,更明显:

 

复制代码 代码如下:

class Program
    {
        static void Main(string[] args)
        {
            int[] array = {1, 3, 5, 7, 90, 2, 4, 6, 8, 10};
            array= GetSort(array);
            for (int i = 0; i < array.Length; i++)
            {
                Console.Write(array[i] + " ");
            }
            Console.ReadKey();
        }
        /// <summary>
        /// 冒泡排序
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        private static int[] GetSort(int[] array)
        {
            //外层循环n-1
            for (int i = 0; i < array.Length-1; i++)
            {
                //内层循环n-1-i
                for (int j = 0; j < array.Length-1-i; j++)
                {
                    if (array[j] > array[j+ 1])
                    {
                        int temp = array[j];
                        array[j] = array[j + 1];
                        array[j + 1] = temp;
                    }  
                }
            }
            return array.ToArray();
        }
    }

相关教程