1. 程式人生 > >C#冒泡排序(完整代碼)

C#冒泡排序(完整代碼)

key 移動 arr logs line 比較 console main 數字

百度百科

冒泡排序是筆試面試經常考的內容,雖然它是這些算法裏排序速度最慢的

原理:從頭開始,每一個元素和它的下一個元素比較,如果它大,就將它與比較的元素交換,否則不動。

這意味著,大的元素總是在向後慢慢移動直到遇到比它更大的元素。所以每一輪交換完成都能將最大值

冒到最後。 原出處:https://www.cnblogs.com/wangjiahong/p/3570465.html 冒泡算法C namespace 數組排序 { class Program { static void Main(string[] args) { int
temp = 0; int[] arr = {23, 44, 66, 76, 98, 11, 3, 9, 7}; 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; } } } Console.WriteLine("排序後的數組:"); foreach (int item in arr) {
Console.Write(item+""); } Console.WriteLine(); Console.ReadKey(); } } }

C#冒泡排序(完整代碼)