欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#冒泡排序示例分享

程序员文章站 2024-02-24 18:21:34
冒泡排序口诀: 升序(从小到大):两for一if;大于连;相 交换;再来个for遍历;外层n-1;内层n-1-i; 说再多不如上代码,更明显: 复制代码 代码如下: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();
        }
    }