C#中如何實現氣泡排序?下面小編為大家整理了c#氣泡排序演算法,希望能幫到大家!
氣泡排序(Bubble Sort)
氣泡排序演算法的運作如下:
1.比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。
2.對每一對相鄰元素作同樣的工作,從開始第一對到結尾的最後一對。在這一點,最後的元素應該會是最大的數。
3.針對所有的元素重複以上的步驟,除了最後一個。
4.持續每次對越來越少的元素重複上面的.步驟,直到沒有任何一對數字需要比較。
平均時間複雜度 |
---|
複製程式碼 程式碼如下:
///
/// 氣泡排序
///
///
///
public static void BubbleSort(int[] arr, int count)
{
int i = count, j;
int temp;
while (i > 0)
{
for (j = 0; j < i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
i--;
}
}
//使用例子
int[] y = new int[] { 1, 32, 7, 2, 4, 6, 10, 8, 11, 12, 3, 9, 13, 5 };
BubbleSort(y, th );
foreach (var item in y)
{
e(item+" ");
}
//1 2 3 4 5 6 7 8 9 10 11 12 13 32
簡單且實用的氣泡排序演算法的控制檯應用程式。執行介面如下:
複製程式碼 程式碼如下:
using System;
using ric;
using ;
using ;
namespace 氣泡排序
{
class Program
{
///
/// 交換兩個整型變數的值
///
///要交換的第一個整形變數
///要交換的第一個整形變數
private static void Reverse(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
static void Main(string[] args)
{
while (true)
{
string[] strInput;//用來接收使用者輸入的字串
int[] intInput;
string[] separator = { ",", " " };//設定分隔符
eLine("請輸入資料,以","或空格分隔,或按"q"退出。");
string str = Line();//接收鍵盤輸入
if (str == "q")
{
return;
}
strInput = t(separator, veEmptyEntries);//將使用者輸入的字串分割為字串陣列
intInput = new Int32[th];
//將字串陣列的每一個元素轉換為整型變數
//轉換時如果出現格式錯誤或溢位錯誤則提示
try
{
for (int i = 0; i < th; i++)
{
intInput[i] = t32(strInput[i]);
}
}
catch (FormatException err)
{
eLine(age);
}
catch(OverflowException err)
{
eLine(age);
}
//排序演算法主體
for (int i = 0; i < th - 1; i++)//這裡的Length要減1否則會超界
{
for (int j = 0; j < th - i - 1; j++)//這裡的Length要減i以減少重複運算
{
//如果元素j比它之後的一個元素大,則交換他們的位置
//如此迴圈直到遍歷完整個陣列
if (intInput[j] > intInput[j + 1])
{
Reverse(ref intInput[j], ref intInput[j + 1]);
}
}
}
string strOutput = "";//用於輸出的字串
foreach (int temp in intInput)
{
strOutput += ring(temp) + ",";
}
eLine("排序後的資料為:rn{0}rn", strOutput);
}
}
}
}