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 SelectionSort() 66 { 67 int min, temp; 68 //每一轮都可以确定一个最小值,排到最前面 69 for (int outer = 0; outer <= upper; outer++) 70 { 71 min = outer; 72 //每一次拿自身数值与排在它后面的数组比较大小,若比它小则记录下标,一轮过后调换数值。 73 for (int inner = outer + 1; inner <= upper; inner++) 74 { 75 if (arr[inner] < arr[min]) min = inner; 76 } 77 temp = arr[outer]; 78 arr[outer] = arr[min]; 79 arr[min] = temp; 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.SelectionSort(); 99 Console.WriteLine("After sorting:"); 100 nums.DisplayElements(); 101 Console.ReadKey(); 102 } 103 } 104 }
运行结果: