C#實現簡單的冒泡排序
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
int[] arrSort = new int[] { 10, 8, 3, 5, 6, 7, 9 };//初始化排序數據
Bubble_Sort(ref arrSort);//調用冒泡排序方法
for (int i = 0; i < arrSort.Length; i++)//輸出排序結果
{
Console.WriteLine("排序的結果為:{0}", arrSort[i]);
}
Console.ReadLine();//暫停輸出窗口
}
/// <summary>
/// C#實現簡單的冒泡排序
/// </summary>
private static void Bubble_Sort(ref int[] arrSort)//ref表示引用型
{
int temp;//預先定義一個中間變量
for (int i = 0; i < arrSort.Length; i++)
{
for (int j = i + 1; j < arrSort.Length; j++)
{
if (arrSort[j] < arrSort[i])//交換數據位置
{
temp = arrSort[j];
arrSort[j] = arrSort[i];
arrSort[i] = temp;
}
}
}
}
}
}
2、輸出的結果如下:
C#實現簡單的冒泡排序