复习冒泡排序法的使用!

冒泡排序法的规律:n个元素排序,需要比较n-1趟(简称t),每趟比较的次数为:元素个数n减去趟t;

例子:

 1 static void Main(string[] args)
2 {
3 int[] shuzu = new int[] { 88, 4, 24, 99, 345, 12 };
4 for (int i = 0; i < shuzu.Length - 1; i++)
5 {
6 for (int j = 0; j < shuzu.Length - 1 - i; j++)
7 {
8 if (shuzu[j] > shuzu[j + 1])
9 {
10 int temp = shuzu[j];
11 shuzu[j] = shuzu[j + 1];
12 shuzu[j + 1] = temp;
13 }
14 }
15 }
16 for (int s = 0; s < shuzu.Length; s++)
17 {
18 Console.WriteLine(shuzu[s]);
19 }
20 Console.Read();
21 }

改进版冒泡排序:

在排序过程中,执行完最后的排序后,数据已全部排序完备,程序可以判断是否完成排序,不再进行多余的比较.

static void Main(string[] args)
{
int[] array = { 23, 45, 16, 7, 42 };
int length = array.Length - 1;
bool isExchanged = false;
for (int i = 0; i < length; i++)
{
isExchanged = false;
for (int j = length; j > i; j--)
{
if (array[j] > array[j - 1])
{
int temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
isExchanged = true;
}
}
if (!isExchanged)//一遍比较过后如果没有进行交换则退出循环
break;
}
foreach (int i in array)
{
Console.WriteLine(i);
}
Console.Read();
}




posted @ 2012-03-18 11:02  ``炯``  阅读(240)  评论(0)    收藏  举报