![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace BubbleSort
6 {
7 class Program
8 {
9 static void Main(string[] args)
10 {
11 TestArray nums = new TestArray(10);
12 #region 初始化数组
13 Random rnd = new Random(100);
14 for (int num = 0; num < 10; num++)
15 {
16 nums.Insert(rnd.Next(0,100));
17 }
18 #endregion
19 Console.WriteLine("Before Sorting: ");
20 nums.DisplayElements();
21 Console.WriteLine("Durring Sorting: ");
22 nums.InsertionSort();
23 Console.WriteLine("After Sorting: ");
24 nums.DisplayElements();
25 Console.ReadLine();
26 }
27 }
28 }
29 public class TestArray
30 {
31 private int[] arr;
32 private int upper;
33 private int numElements;
34 public TestArray(int size)
35 {
36 arr = new int[size];
37 upper = size - 1;
38 numElements = 0;
39 }
40 public void Insert(int item)
41 {
42 arr[numElements] = item;
43 numElements++;
44 }
45 public void DisplayElements()
46 {
47 for (int num = 0; num <= upper; num++)
48 {
49 Console.Write(arr[num]+" ");
50 }
51 Console.WriteLine();
52 }
53 public void Clear()
54 {
55 for (int num = 0; num <= upper; num++)
56 {
57 arr[num] = 0;
58 }
59 numElements = 0;
60 }
61 //插入排序算法
62 public void InsertionSort()
63 {
64 int inner, temp;
65 for(int outer=1;outer<=upper;outer++)
66 {
67 inner=outer;
68 temp=arr[outer];
69 while(inner>0 && arr[inner-1]>=temp)
70 {
71 arr[inner]=arr[inner-1];
72 inner-=1;
73 }
74 arr[inner]=temp;
75 this.DisplayElements();
76 }
77 }
78 }
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace BubbleSort
6 {
7 class Program
8 {
9 static void Main(string[] args)
10 {
11 TestArray nums = new TestArray(10);
12 #region 初始化数组
13 Random rnd = new Random(100);
14 for (int num = 0; num < 10; num++)
15 {
16 nums.Insert(rnd.Next(0,100));
17 }
18 #endregion
19 Console.WriteLine("Before Sorting: ");
20 nums.DisplayElements();
21 Console.WriteLine("Durring Sorting: ");
22 nums.InsertionSort();
23 Console.WriteLine("After Sorting: ");
24 nums.DisplayElements();
25 Console.ReadLine();
26 }
27 }
28 }
29 public class TestArray
30 {
31 private int[] arr;
32 private int upper;
33 private int numElements;
34 public TestArray(int size)
35 {
36 arr = new int[size];
37 upper = size - 1;
38 numElements = 0;
39 }
40 public void Insert(int item)
41 {
42 arr[numElements] = item;
43 numElements++;
44 }
45 public void DisplayElements()
46 {
47 for (int num = 0; num <= upper; num++)
48 {
49 Console.Write(arr[num]+" ");
50 }
51 Console.WriteLine();
52 }
53 public void Clear()
54 {
55 for (int num = 0; num <= upper; num++)
56 {
57 arr[num] = 0;
58 }
59 numElements = 0;
60 }
61 //插入排序算法
62 public void InsertionSort()
63 {
64 int inner, temp;
65 for(int outer=1;outer<=upper;outer++)
66 {
67 inner=outer;
68 temp=arr[outer];
69 while(inner>0 && arr[inner-1]>=temp)
70 {
71 arr[inner]=arr[inner-1];
72 inner-=1;
73 }
74 arr[inner]=temp;
75 this.DisplayElements();
76 }
77 }
78 }