C#算法基础之冒泡排序
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace ConsolePractice 8 { 9 class CArray 10 { 11 private int[] arr; 12 //数组大小 13 private int upper; 14 //下标 15 private int numElements; 16 17 /// <summary> 18 /// 初始化数组参数 19 /// </summary> 20 /// <param name="size"></param> 21 public CArray(int size) 22 { 23 arr = new int[size]; 24 upper = size - 1; 25 numElements = 0; 26 } 27 28 /// <summary> 29 /// 插入方法 30 /// </summary> 31 /// <param name="item">存储的数</param> 32 public void Insert(int item) 33 { 34 arr[numElements] = item; 35 numElements++; 36 } 37 38 /// <summary> 39 /// 输出方法 40 /// </summary> 41 public void DisplayElements() 42 { 43 for (int i = 0; i <= upper; i++) 44 { 45 Console.Write(arr[i] + " "); 46 } 47 Console.WriteLine(); 48 } 49 50 /// <summary> 51 /// 清除数组 52 /// </summary> 53 public void Clear() 54 { 55 for (int i = 0; i <= upper; i++) 56 { 57 arr[i] = 0; 58 } 59 numElements = 0; 60 } 61 62 /// <summary> 63 /// 冒泡排序算法 64 /// </summary> 65 public void BubbleSort() 66 { 67 int temp; 68 for (int outer = upper; outer >= 1; outer--) 69 { 70 //每一轮最后的一个数值可以确定,所以每一轮都减少1次。按照outer判定。 71 for (int inner = 0; inner <= outer - 1; inner++) 72 { 73 if (arr[inner] > arr[inner + 1]) 74 { 75 temp = arr[inner]; 76 arr[inner] = arr[inner + 1]; 77 arr[inner + 1] = temp; 78 } 79 } 80 this.DisplayElements(); 81 } 82 } 83 } 84 85 class C_shape 86 { 87 static void Main() 88 { 89 CArray nums = new CArray(10); 90 Random rnd = new Random(100); 91 for (int i = 0; i < 10; i++) 92 { 93 nums.Insert(rnd.Next(0,100)); 94 } 95 Console.WriteLine("Before sorting:"); 96 nums.DisplayElements(); 97 Console.WriteLine("During sorting:"); 98 nums.BubbleSort(); 99 Console.WriteLine("After sorting:"); 100 nums.DisplayElements(); 101 Console.ReadKey(); 102 } 103 } 104 }
运行结果: