首页 > 编程 > C# > 正文

c#冒泡排序示例分享

2020-01-24 02:47:53
字体:
来源:转载
供稿:网友

冒泡排序口诀:

升序(从小到大):两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();
        }
    }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表