C# For循环与冒泡算法

 1 //建立一个控制台程序,把下面代码复制进去 Ctrl + F5运行

 2 

 3 using System;

 4 using System.Collections.Generic;

 5 using System.Linq;

 6 using System.Text;

 7 

 8 namespace ConsoleApplication1

 9 {

10     class Program

11     {

12         static void Main(string[] args)

13         {

14             int[] my = new int[10];  //定义一个有十个元素的整形数组

15             int r;

16             Random rd = new Random(); //实例random类(用于生成随机数)

17             

18             //随机数生成

19             for (int t = 0; t < 9; t++)

20             {

21                 my[t] = rd.Next(30);   //生成30以内的随机数.

22                 Console.WriteLine(my[t]);

23             }

24             

25             //冒泡算法(可以优化)

26             for (int s = 0; s < 9; s++)

27             {

28                 for (int j = 0; j < 9; j++)

29                 {

30                     if (my[j] > my[j + 1])

31                     {

32                         r = my[j];

33                         my[j] = my[j + 1];

34                         my[j + 1] = r;

35                     }

36                 }

37             }

38             

39             //输出数组

40             for (int w = 0; w < 9; w++)

41             {

42                 Console.Write(my[w] + ",");

43             }

44         }

45     }

46 }

你可能感兴趣的:(for循环)