基本原理:
//两两相邻
//不停比较
//不停交换
//比较n轮
代码如下: int[] Array = new int[] { 7, 3, 1, 6, 2, 8,2};
for (int i = 0; i < Array.Length; i++)
{
Console.Write(Array[i]);
}
for (int j=0;j<Array.Length; j++)
{
for (int i = 0; i < Array.Length - 1; i++)
{
if (Array[i] > Array[i + 1])
{
int temp = Array[i];
Array[i] = Array[i + 1];
Array[i + 1] = temp;
}
}
}
for (int i = 0; i < Array.Length; i++)
{
Console.WriteLine(Array[i]);
}
代码优化:
1.确定位置的数字就不用再比较了,确定了一轮后,极值(最大或最小)
已经放在末尾了,所以每完成n轮,后面位置的数就不用再参与了。
for (int j=0;j<Array.Length; j++)
{
for (int i = 0; i < Array.Length - 1-j; i++)//减去j
{
if (Array[i] > Array[i + 1])
{
int temp = Array[i];
Array[i] = Array[i + 1];
Array[i + 1] = temp;
}
}
2.特殊情况的优化(提高计算机性能)
bool isSort=false;
for (int j=0;j<Array.Length; j++)
{ isSort=false;
for (int i = 0; i < Array.Length - 1; i++)
{
if (Array[i] > Array[i + 1])
{ isSort=true;
int temp = Array[i];
Array[i] = Array[i + 1];
Array[i + 1] = temp;
}
}
if(isSort==false){
break;//如果一轮结束后,如果isSort这个标识还是false,证明已经排好序。
}
}