一、封装两种冒泡排序的方法
public class SortBy { /// <summary> /// 方式一:从后往前交换 /// </summary> /// <param name="array"></param> public static void BubbleSort(int[] array) { int i, j, temp; int len = array.Length; for (i = 0; i < len - 1; i++) { for (j = len - 1; j > i; --j) { if (array[j] < array[j - 1]) { temp = array[j]; array[j] = array[j - 1]; array[j - 1] = temp; } } } } /// <summary> /// 方式二:从前往后交换 /// </summary> /// <param name="arr"></param> public static void BubbleSortAsc(int[] arr) { int temp = 0; for (int i = 0; i < arr.Length - 1; i++) { for (int j = 0; j < arr.Length - 1 - i; j++) { if (arr[j+1] < arr[j]) { temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } }
二、控制台调用
class Program { static void Main(string[] args) { int[] arr = { 1, 3, 5, 10, 999, 632, -123, 985, 45, 32 }; SortBy.BubbleSortAsc(arr); int[] arr2 = { 10, 30, 5, 110, 99, 32, -123, -985, 45, 32 }; SortBy.BubbleSort(arr2); System.Console.WriteLine(string.Join(",", arr2)+Environment.NewLine+string.Join(",", arr)); } }
三、输出效果