冒泡排序和选择排序学习笔记
static void Main(string[] args) { int[] nums = new int[20]; Random r = new Random(); for (int i = 0; i < nums.Length; i++) { nums[i] = r.Next(0, 100); } Sort1(ref nums); for (int i = 0; i < nums.Length; i++) { Console.Write(nums[i] + " "); } Console.ReadKey(); } /// <summary> /// 冒泡排序 /// </summary> /// <param name="n"></param> static void Sort1(ref int[] n) { for (int i = 0; i < n.Length; i++) { int count = 0; for (int j = 0; j < n.Length - i - 1; j++) { if (n[j] > n[j + 1]) { ChangeNum(ref n[j], ref n[j + 1]); count++; } } if (count == 0) break; } } /// <summary> /// 选择排序 /// </summary> /// <param name="n"></param> static void Sort2(ref int[] n) { for (int i = 0; i < n.Length; i++) { int index = 0; for (int j = 1; j < n.Length - i; j++) { if (n[index] < n[j]) index = j; } if(index != n.Length - i - 1) ChangeNum(ref n[index], ref n[n.Length - i - 1]); } } static void ChangeNum(ref int m,ref int n) { m += n; n = m - n; m -= n; }