纸上得来终觉浅,绝知此事要躬行
冒泡排序,通俗点来说,就是通过一连串的相邻数比较交换,将数组中较小的数不断的往数组的前端“吐”。
话不多说,直接上代码。以下代码使用的是C#语言。
class Program
{
private static void Swap(ref int a, ref int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
private static void BubbleSort(int[] array)
{
for (int i = 0; i < array.Length; i++)
for (int j = array.Length - 1; j > i; j--)
{
if (array[j] < array[j - 1])
Swap(ref array[j], ref array[j - 1]);
}
}
static void Main(string[] args)
{
int[] a = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
Console.Write("before: ");
for (int i = 0; i < a.Length; i++)
Console.Write(a[i] + " ");
Console.WriteLine(" ");
BubbleSort(a);
Console.Write("after: ");
for (int i = 0; i < a.Length; i++)
Console.Write(a[i] + " ");
Console.Read();
}
}