冒泡排序(Bubble Sort)
冒泡排序算法的運作如下:
1.比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。
2.對每一對相鄰元素作同樣的工作,從開始第一對到結尾的最后一對。在這一點,最后的元素應該會是最大的數。
3.針對所有的元素重復以上的步驟,除了最后一個。
4.持續每次對越來越少的元素重復上面的步驟,直到沒有任何一對數字需要比較。
平均時間復雜度 | ![]() |
---|
簡單且實用的冒泡排序算法的控制臺應用程序。運行界面如下:
namespace 冒泡排序
{
class Program
{
/// <summary>
/// 交換兩個整型變量的值
/// </summary>
/// <param name="a">要交換的第一個整形變量</param>
/// <param name="b">要交換的第一個整形變量</param>
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 = { ",", " " };//設置分隔符
Console.WriteLine("請輸入數據,以/",/"或空格分隔,或按/"q/"退出。");
string str = Console.ReadLine();//接收鍵盤輸入
if (str == "q")
{
return;
}
strInput = str.Split(separator, StringSplitOptions.RemoveEmptyEntries);//將用戶輸入的字符串分割為字符串數組
intInput = new Int32[strInput.Length];
//將字符串數組的每一個元素轉換為整型變量
//轉換時如果出現格式錯誤或溢出錯誤則提示
try
{
for (int i = 0; i < strInput.Length; i++)
{
intInput[i] = Convert.ToInt32(strInput[i]);
}
}
catch (FormatException err)
{
Console.WriteLine(err.Message);
}
catch(OverflowException err)
{
Console.WriteLine(err.Message);
}
//排序算法主體
for (int i = 0; i < intInput.Length - 1; i++)//這里的Length要減1否則會超界
{
for (int j = 0; j < intInput.Length - 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 += Convert.ToString(temp) + ",";
}
Console.WriteLine("排序后的數據為:/r/n{0}/r/n", strOutput);
}
}
}
}
|
新聞熱點
疑難解答