冒泡排序
时间复杂度
初始状态是正序的,一趟扫描即可完成排序,关键字比较次数C和记录移动次数M均达到最小值: ,
。
若初始状态是反序的,需要进行 趟排序。每趟排序要进行
次关键字的比较(1≤i≤n-1),且每次比较都必须移动记录三次来达到交换记录位置。在这种情况下,比较和移动次数均达到最大值
,
冒泡排序的最坏时间复杂度为 。
综上,因此冒泡排序总的平均时间复杂度为 。
static void Main(string[] args) { int[] arrayNumber = new int[] { 3, 2, 1, 4, 5, 6 }; BubbleSort(arrayNumber); Console.ReadKey(); } protected static void BubbleSort(int[] array) { int temp; for (int i = 0; i < array.Length; i++) { for (int j = i + 1; j < array.Length; j++) { if (array[j] < array[i]) { temp = array[j]; array[j] = array[i]; array[i] = temp; } } PrintList(array); } } protected static void PrintList(int[] array) { foreach (var item in array) { Console.Write(string.Format("{0} ", item)); } Console.WriteLine(); }