1.冒泡排序
using System; using System.Collections.Generic; namespace app01 { class _01冒泡排序 { static void Main() { var list = new List<int>(); Random random = new Random(); for (int i = 0; i < 20; i++) list.Add(random.Next(1, 101)); PrintList<int>(list); BubbleSort(list); PrintList<int>(list); } // 冒泡排序 static void BubbleSort(List<int> list) { for (int i = 0; i < list.Count; i++) { for (int j = 0; j < list.Count - 1; j++) { if (list[j + 1] < list[j]) { var temp = list[j]; list[j] = list[j + 1]; list[j + 1] = temp; } } } } // 打印list static void PrintList<T>(List<T> list) { foreach (var item in list) Console.Write(item+" "); Console.WriteLine(); } } }
2. 选择排序
using System; using System.Collections.Generic; namespace app01 { class _02选择排序 { static void Main() { var list = new List<int>(); Random random = new Random(); for (int i = 0; i < 20; i++) list.Add(random.Next(1, 101)); PrintList<int>(list); SelectSort(list); PrintList<int>(list); } static void SelectSort(List<int> list) { for (int i = 0; i < list.Count-1; i++) { int min_index = i; for (int j = i+1; j < list.Count; j++) { if (list[j] < list[min_index]) min_index = j; } var temp = list[min_index]; list[min_index] = list[i]; list[i] = temp; } } // 打印list static void PrintList<T>(List<T> list) { foreach (var item in list) Console.Write(item + " "); Console.WriteLine(); } } }