C#氣泡排序
阿新 • • 發佈:2022-04-20
升序:
public static List<int> BubbleSortAsc(List<int> list) { for (int i = 0; i < list.Count - 1; i++) { for (int j = 0; j < list.Count-1-i; j++) { if (list[j] > list[j + 1]) {int temp = list[j + 1]; list[j + 1] = list[j]; list[j] = temp; } } Console.Write($"第{i + 1}遍:"); foreach (var item in list) { Console.Write(item + ""); } Console.WriteLine(); } return list; }
降序:
public static List<int> BubbleSortDesc(List<int> list) { for (int i = 0; i < list.Count-1; i++) { for (int j = list.Count-1; j > i; j--) { if (list[j] > list[j - 1]) { int temp = list[j]; list[j] = list[j - 1]; list[j - 1] = temp; } } Console.Write($"第{i+1}遍:"); foreach (var item in list) { Console.Write(item + " "); } Console.WriteLine(); } return list; }