冒泡排序

来源:互联网 发布:vscode webpack插件 编辑:程序博客网 时间:2024/05/15 20:13
namespace 冒泡排序
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] num = new int[10] { 1, 3, 5, 2, 4, 6, 8, 7, 9, 0 };
            Console.WriteLine("请输入排列类型1代表升序,2代表降序");
           int sortedMethod=Convert.ToInt32( Console.ReadLine());
            if (sortedMethod == 1)      //升序排列
            {
                for (int i = 0; i < num.Length - 1; i++)
                {
                    for (int j = 0; j < num.Length - 1 - i; j++)
                    {
                        if (num[j] > num[j + 1])//如果前面的数大于后面的数
                        {
                            int temp = num[j];//将前面的数给给一个临时变量
                            num[j] = num[j + 1];//将后面的的数给前面的数
                            num[j + 1] = temp;
                            //就是将两个数换了位置把大的数放在了后面
                        }
                    }
                }
            }
            if (sortedMethod == 2)      //降序排列
            {
                for (int i = 0; i < num.Length - 1; i++)
                {
                    for (int j = 0; j < num.Length - 1 - i; j++)
                    {
                        if (num[j] < num[j + 1])//如果后面的数大于前面的数
                        {
                            int temp = num[j];
                            num[j] = num[j + 1];
                            num[j + 1] = temp;
                            //把小的数放在后面
                        }
                    }
                }
            }
            Console.WriteLine(num);
            Console.ReadKey();
        }
    }
}
原创粉丝点击