理解:
假设有5个气泡,每进行一次遍历,就从最低端开始两两比较,将较大的气泡冒到上面的位置,有n个气泡就进行n-1次比较,下图是冒泡排序的工作原理:
代码如下:
static void BubbleSort(int[] arr)
{
for (int i = 0; i < arr.Length-1; i++)
{
for (int j = 0; j < arr.Length - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
优化方法1:添加一个标志位unaltered,当数组在一次冒泡后,没有发生任何改变,则说明这个数组已经排好了,直接返回,代码:
static void BubbleSort_One(int[] arr)
{
bool unaltered = true;
for (int i = 0; i < arr.Length-1; i++)
{
unaltered = true;
for (int j = 0; j < arr.Length - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
unaltered = false;
}
}
if (unaltered)
return;
}
}
优化方法2:在内层循环中记录下最后一次交换发生的位置,下一次循环时就不用再比较该位置后面的数了,因为其不再发生交换,已经是有序的了,但要注意这时内层循环的交换次数不应该再减去已经交换了的数据个数,否则会交换次数不足的情况,这时的交换次数完全取决于标志位的记录。代码如下:
static void BubbleSort_Two(int[] arr)
{
bool unaltered = true;
int curIndex = arr.Length;
int newIndex = 0;
for (int i = 0; i < arr.Length-1; i++)
{
unaltered = true;
for (int j = 0; j < curIndex - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
newIndex = j + 1;
unaltered = false;
}
}
curIndex = newIndex;
if (unaltered)
return;
}
}
完整代码如下:
static void Main(string[] args)
{
int[] arr = new int[10] { 5, 78, 96, 52, 569, 22, 36, 48, 99, 75 };
Console.WriteLine("Before sort:");
Show(arr);
Console.WriteLine("After sort:");
BubbleSort(arr);
Show(arr);
}
static void Show(int[] arr)
{
foreach (var item in arr)
Console.Write(item + "\t");
Console.WriteLine();
}
static void BubbleSort(int[] arr)
{
for (int i = 0; i < arr.Length-1; i++)
{
for (int j = 0; j < arr.Length - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
static void BubbleSort_One(int[] arr)
{
bool unaltered = true;
for (int i = 0; i < arr.Length-1; i++)
{
unaltered = true;
for (int j = 0; j < arr.Length - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
unaltered = false;
}
}
if (unaltered)
return;
}
}
static void BubbleSort_Two(int[] arr)
{
bool unaltered = true;
int curIndex = arr.Length;
int newIndex = 0;
for (int i = 0; i < arr.Length-1; i++)
{
unaltered = true;
for (int j = 0; j < curIndex - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
newIndex = j + 1;
unaltered = false;
}
}
curIndex = newIndex;
if (unaltered)
return;
}
}