这个算法的名字由来是因为越大的元素会经由交换慢慢“浮”到数列的顶端,故名。
冒泡算法C#namespace 数组排序{ class PRogram { static void Main(string[] args) { int temp = 0; int[] arr = {23, 44, 66, 76, 98, 11, 3, 9, 7}; #region该段与排序无关 Console.WriteLine("排序前的数组:"); foreach (int item in arr) { Console.Write(item + ""); } Console.WriteLine(); #endregion for (int i = 0; i < arr.Length - 1; i++) { #region将大的数字移到数组的arr.Length-1-i for (int j = 0; j < arr.Length - 1 - i; j++) { if (arr[j] > arr[j + 1]) { temp = arr[j + 1]; arr[j + 1] = arr[j]; arr[j] = temp; } } #endregion } Console.WriteLine("排序后的数组:"); foreach (int item in arr) { Console.Write(item+""); } Console.WriteLine(); Console.ReadKey(); } }}
新闻热点
疑难解答