冒泡排序 升序 降序(笔试)

原数组为:[4,5,6,7,81,23,21,45,9]请用冒泡排序算法实现降序排序!

升序(从小到大)

 int[] numarr = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
            for (int i = 0; i < numarr.Length - 1; i++)
            {
                for (int j = 0; j < numarr.Length - 1 - i; j++)
                {
                    if (numarr[j] > numarr[j + 1])
                    {
                        int temp = numarr[j];
                        numarr[j] = numarr[j + 1];
                        numarr[j + 1] = temp;
                    }
                }
            }

            for (int i = 0; i < numarr.Length; i++)
            {
                Console.WriteLine(numarr[i]);

            }
            Console.ReadKey();

降序(从大到小)

int[] numarr = { 4, 5, 6, 7, 81, 23, 21, 45, 9};
            for (int i = 0; i < numarr.Length - 1; i++)
            {
                for (int j = 0; j < numarr.Length - 1 - i; j++)
                {
                    if (numarr[j] < numarr[j + 1])
                    {
                        int jia = numarr[j];
                        numarr[j] = numarr[j + 1];
                        numarr[j + 1] = jia;
                    }
                }
            }
            for (int i = 0; i < numarr.Length; i++)
            {
                Console.WriteLine(numarr[i]);
            }
            Console.ReadKey();

 

posted @ 2021-05-06 18:39  好记性不如烂笔头-贾  阅读(389)  评论(0编辑  收藏  举报