当前位置:主页 > 软件编程 > .NET代码 >

c#冒泡排序示例分享

时间:2020-10-02 10:19:12 | 栏目:.NET代码 | 点击:

冒泡排序口诀:

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

您可能感兴趣的文章:

相关文章