之前的排序:
int temp = 0;
for (int i = arr.Length - 1; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
能夠看出,由于有兩層for循環(huán)的存在,使得整個排序必須要進(jìn)行(n - 2)!次判斷,即使第一次產(chǎn)生的數(shù)組就是已經(jīng)排好序的。
對這個版本的冒泡排序進(jìn)行優(yōu)化:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _0301數(shù)組的冒泡排序_優(yōu)化
{
class Program
{
static void Main(string[] args)
{
int len = 0; //數(shù)組大小
int min = 0; //數(shù)組下界
int max = 0; //數(shù)組上界
Console.WriteLine("下面將產(chǎn)生一個隨機(jī)數(shù)組");
//接收數(shù)組大小
do
{
Console.WriteLine("請輸入數(shù)組大小,它必須是一個小于等于10的正整數(shù):");
len = int.Parse(Console.ReadLine());
} while ((len <= 0) || (len > 10));
//接收數(shù)組下界
Console.WriteLine("請輸入數(shù)組下界,它必須是一個整數(shù):");
min = int.Parse(Console.ReadLine());
//接收數(shù)組上界
do
{
Console.WriteLine("請輸入數(shù)組上界,它必須是一個整數(shù),并且比數(shù)組小值大,且能讓數(shù)組容納{0}個數(shù):", len);
max = int.Parse(Console.ReadLine());
} while ((max <= min) || ((max - min + 1) < len));
Console.WriteLine();
Console.WriteLine("數(shù)組長度:{0}\n數(shù)組下界:{1}\n數(shù)組上界:{2}", len, min, max);
Console.WriteLine("生成數(shù)組如下:");
int iSeed = 6;
Random ra = new Random(iSeed);
int[] arr = new int[len];
//打印原數(shù)組的值
for (int i = 0; i < arr.Length; i++)
{
arr[i] = ra.Next(min, max);
Console.Write(arr[i]);
if (i < arr.Length - 1)
{
Console.Write(",");
}
else
{
Console.WriteLine();
}
}
//開始進(jìn)行數(shù)組排序
Console.WriteLine("數(shù)組產(chǎn)生完畢,開始排序");
Console.WriteLine();
#region 原有排序,這種排序必須要比較(n -2)!次
//int temp = 0;
//for (int i = arr.Length - 1; i > 0; i--)
//{
// for (int j = 0; j < i; j++)
// {
// if (arr[j] > arr[j + 1])
// {
// temp = arr[j + 1];
// arr[j + 1] = arr[j];
// arr[j] = temp;
// }
// }
//}
#endregion
//這種排序多比較(n - 2)!次,但如果當(dāng)前已是優(yōu)排序結(jié)果則直接停止比較
int temp = 0;
bool swapped = true;
do
{
swapped = false;
for (int i = 0; i < arr.Length - 1; i++)
{
if (arr[i] > arr[i + 1])
{
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
//打印排序后的結(jié)果
Console.WriteLine("排序后結(jié)果:");
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i]);
if (i < arr.Length - 1)
{
Console.Write(",");
}
else
{
Console.WriteLine();
}
}
Console.WriteLine("程序結(jié)束");
Console.ReadKey();
}
}
}
這個版本的排序?qū)⑼鈱友h(huán)改成了do...while()實現(xiàn),并設(shè)置一個標(biāo)識變量swapped,如果本次內(nèi)部循環(huán)未進(jìn)行一次數(shù)據(jù)置換則說明數(shù)組序列已實現(xiàn)優(yōu),立刻結(jié)束外層循環(huán)。這種排序多比較(n - 2)!次,但如果當(dāng)前已是優(yōu)排序結(jié)果則直接停止比較。
其實外層循環(huán)是for循環(huán)也可以實現(xiàn)這種效果,但相對來說do...while()寫起來更優(yōu)雅一些。