c#冒泡排序算法
C#中如何實現(xiàn)冒泡排序?下面小編為大家整理了c#冒泡排序算法,希望能幫到大家!
冒泡排序(Bubble Sort)
冒泡排序算法的運作如下:
1.比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。
2.對每一對相鄰元素作同樣的工作,從開始第一對到結(jié)尾的最后一對。在這一點,最后的元素應(yīng)該會是最大的數(shù)。
3.針對所有的元素重復(fù)以上的步驟,除了最后一個。
4.持續(xù)每次對越來越少的元素重復(fù)上面的步驟,直到?jīng)]有任何一對數(shù)字需要比較。
| 平均時間復(fù)雜度 |
|---|
復(fù)制代碼 代碼如下:
/pic/
/pic/ 冒泡排序
/pic/
/pic/
/pic/
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--;
}
}
/pic/p>
int[] y = new int[] { 1, 32, 7, 2, 4, 6, 10, 8, 11, 12, 3, 9, 13, 5 };
BubbleSort(y, y.Length );
foreach (var item in y)
{
Console.Write(item+" ");
}
/pic/p>
簡單且實用的冒泡排序算法的控制臺應(yīng)用程序。運行界面如下:
復(fù)制代碼 代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 冒泡排序
{
class Program
{
/pic/
/pic/ 交換兩個整型變量的值
/pic/
/pic/要交換的第一個整形變量
/pic/要交換的第一個整形變量
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;/pic/p>
int[] intInput;
string[] separator = { ",", " " };/pic/p>
Console.WriteLine("請輸入數(shù)據(jù),以","或空格分隔,或按"q"退出。");
string str = Console.ReadLine();/pic/p>
if (str == "q")
{
return;
}
strInput = str.Split(separator, StringSplitOptions.RemoveEmptyEntries);/pic/p>
intInput = new Int32[strInput.Length];
/pic/p>
/pic/p>
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);
}
/pic/p>
for (int i = 0; i < intInput.Length - 1; i++)/pic/p>
{
for (int j = 0; j < intInput.Length - i - 1; j++)/pic/p>
{
/pic/p>
/pic/p>
if (intInput[j] > intInput[j + 1])
{
Reverse(ref intInput[j], ref intInput[j + 1]);
}
}
}
string strOutput = "";/pic/p>
foreach (int temp in intInput)
{
strOutput += Convert.ToString(temp) + ",";
}
Console.WriteLine("排序后的數(shù)據(jù)為:rn{0}rn", strOutput);
}
}
}
}
【c#冒泡排序算法】相關(guān)文章:
c#快速排序算法11-16
C#排序算法之快速排序01-07
C#排序算法之堆排序11-16
C語言冒泡排序算法實例12-19
C++冒泡排序算法實例詳解10-13
冒泡排序算法原理及JAVA實現(xiàn)代碼方法09-26
C語言經(jīng)典冒泡排序法12-09