冒泡排序算法举例



   static void Main(string[] args)
        {
           int[]a= Read();//读数据
           Sort(ref a);//排序
           Write(a);//输出数据 
        }

 读数据
 1         /// <summary>
2 /// 读数据
3 /// </summary>
4 /// <returns></returns>
5 public static int[] Read()
6 {
7 int i;
8
9 int[] a = new int[5];
10 for (int j = 0; j < 5; j++)
11 {
12 i = Int32.Parse(Console.ReadLine());
13 a[j] = i;
14 }
15 return a;
16
17 }
对数据排序
 1  public static void Sort(ref int[] a)
2 {
3 for (int m = 0; m < a.Length; m++)
4 {
5 for (int j = m + 1; j < a.Length; j++)
6 {
7 if (a[m] > a[j])
8 {
9 int temp; temp = a[m];
10 a[m] = a[j]; a[j] = temp;
11 }
12 }
13 }
14 }


 

输出数据
1 public static void Write(int[] a)
2 {
3 for (int k = 0; k < a.Length; k++)
4 {
5 Console.WriteLine(a[k]);
6 }
7 }

双向冒泡算法举例:

View Code
 1 static void Main(string[] args)
2 {
3 int i;
4 int[] r = Read();
5 int start=0,end=r.Length-1;
6 while(start<=end)
7 {
8 for (i = start; i < r.Length-1; i++)
9 {
10 if(r[i]>r[i+1])
11 {
12 int temp;
13 temp = r[i];
14 r[i] = r[i + 1];
15 r[i + 1] = temp;
16 }
17 }
18 for (i = end; i > start; i--)
19 {
20 if (r[i] < r[i-1])
21 {
22 int temp;
23 temp = r[i];
24 r[i] = r[i - 1];
25 r[i - 1] = temp;
26
27 }
28 }
29 start++;
30
31 }
32 for (int j = 0; j < r.Length; j++)
33 {
34 Console.WriteLine(r[j]);
35 }
36
37
38 }


      

凡事用心去做,认真对待!
原文地址:https://www.cnblogs.com/lsysunbow/p/2369395.html