for的冒泡排序练习题

这是一个冒泡排序的方法,请汲取其中的思想。
有一组数: 1,2,3,4,5,6
请将这组数用降序排列。
我们可以将数组里面的数两两相比,如果第二个数比第一个数大,那么将第二个数值与第一个数值交换,然后让其循环比较。
[1,2,3,4,5,6]               [2,3,4,5,6,1]             [3,4,5,6,2,1]            [4,5,6,3,2,1]              [5,6,4,3,2,1]

[2,1,3,4,5,6]               [3,2,4,5,6,1]             [4,3,5,6,2,1]            [5,4,6,3,2,1]              [6,5,4,3,2,1]

[2,3,1,4,5,6]               [3,4,2,5,6,1]             [4,5,3,6,2,1]            [5,6,4,3,2,1]              [6,5,4,3,2,1]

[2,3,4,1,5,6] →→→→   [3,4,5,2,6,1] →→→→ [4,5,6,3,2,1] →→→→[5,6,4,3,2,1] →→→→  [6,5,4,3,2,1]

[2,3,4,5,1,6]               [3,4,5,6,2,1]             [4,5,6,3,2,1]            [5,6,4,3,2,1]              [6,5,4,3,2,1]

[2,3,4,5,6,1]               [3,4,5,6,2,1]             [4,5,6,3,2,1]            [5,6,4,3,2,1]              [6,5,4,3,2,1]

我们可以先定义一个数组n[]将数据赋予n[]; 通过数组运行循环下标来控制数据比较,既n[0]<n[1];这样我们就得到了判定条件,既

if(n[0]<n[1])

{
  int m = 0;        
  m=n[0];
  n[0] = n[1];
  n[1] = m;                      
 }

在图中红字可以看出 我们通过两位数比较n[0]<n[1]n[1]<n[2]n[2]<n[3]n[3]<n[4]n[4]<n[5]n[i]<n[i+1] 循环。

这里我们输入了6个数比较了5次,那么长度就是(n.length-1)

得到方法:

static void Main(string[] args)
        {
            int[] n=new int[]{1,2,3,4,5,6};               //定义一个数组
            for (int i = 0; i < n.Length-1; i++)                   //一共比较了几轮
            {
                for (int j = 0; j < n.Length - 1; j++)            //一轮中比较几次
                {
                    if (n[j]<n[j+1])
                    {
                        int m = 0;
                        m=n[j];
                        n[j] = n[j + 1];
                        n[j+ 1] = m;                      
                    }
                }  
            }
            //for (int k = 0; k < n.Length; k++)
            //{
            //    Console.WriteLine(n[k]);
            //}
            foreach (int item in n)                       //用for和foreach都行,经过上面的步骤我们已经把n重新排序好了,输出n。
            Console.WriteLine(item);
            Console.ReadLine();
                }

还一种快速方法供大家参考:

  static void Main(string[] args)
        {
               int[] n=new int[]{1,2,3,4,5,6};
            for (int i = 0; i < n.Length-1; i++)
            {
                for (int j = i; j < n.Length - 1; j++)
                {
                    if (n[j]<n[j+1])
                    {
                        int m = 0;
                        m=n[i];
                        n[i] = n[j + 1];
                        n[j+ 1] = m;            
                    }
                }      
            }           
            foreach (int item in n)
                Console.WriteLine(item);
            Console.ReadLine();

原文地址:https://www.cnblogs.com/18553325o9o/p/4431623.html