演算法描述 1.由數組第一位數值開始與相鄰數值進行比較,每次將比較後大的數值後移。最後將會把數組中最大值移動到數組最後; 2.依次對數組中未排序序列重覆進行比較排序,將比較後的最大值移動到未排序序列的最後; 代碼實現 完整代碼 ...
演算法描述
1.由數組第一位數值開始與相鄰數值進行比較,每次將比較後大的數值後移。最後將會把數組中最大值移動到數組最後;
2.依次對數組中未排序序列重覆進行比較排序,將比較後的最大值移動到未排序序列的最後;
代碼實現
/* 例如:對數組:{ 5,4,3,2,1 }進行比較 第一輪:{ 4,3,2,1,5 } :共比較四次 第二輪:{ 3,2,1,4,5 } :共比較三次 第三輪:{ 2,1,3,4,5 } :共比較二次 第四輪:{ 1,2,3,4,5 } :共比較一次 */ public void Bubble(int[] arr) { int temp; bool flag; for (int i = 0; i < arr.Length - 1; i++) // 迴圈輪數 { flag = true; for (int j = 0; j < arr.Length - i - 1; j++) // 比較次數 { if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; flag = false; } } if (flag == true) { break; } } Console.Write("冒泡排序:"); foreach (int item in arr) { Console.Write(item + " "); } }
完整代碼
using System; namespace BubbleSortApplication { class Program { static void Main(string[] args) { var setArray = new SetArray(); var bubbleSort = new BubbleSort(); int[] arr = setArray.GetArray(); bubbleSort.Bubble(arr); Console.ReadLine(); } } class SetArray // 數組類 { public int[] GetArray() { int length; // 數組長度 int[] arr; Console.WriteLine("請輸入數組長度:"); length = Convert.ToInt32(Console.ReadLine()); arr = new int[length]; for (int i = 0; i <= length - 1; i++) { Console.Write("請輸入數組第{0}位數值:", i); arr[i] = Convert.ToInt32(Console.ReadLine()); } Console.Clear(); Console.Write("arr[] = {"); foreach (int item in arr) { Console.Write(item + " "); } Console.Write("}\n"); return arr; } } class BubbleSort // 冒泡排序 { public void Bubble(int[] arr) { int temp; bool flag; for (int i = 0; i < arr.Length - 1; i++) { flag = true; for (int j = 0; j < arr.Length - i - 1; j++) { if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; flag = false; } } if (flag == true) { break; } } Console.Write("冒泡排序:"); foreach (int item in arr) { Console.Write(item + " "); } } } }