让数组中的元素两两比较(第i个与第i+1个比较),经过(i-1)遍两两比较,
{
for(int j=0;j<num.length-1-i;j++)
{
if(num[j]<num[j+1])
{
int temp=num[j];
num[j]=num[j+1];
num[j+1]=temp;
}
}
}
例题:
int[] scores = { 19, 32, 43, 6, 71, 91, 10 }; //由大到小排序
for (int i = 0; i < scores.Length; i++)//控制比较的趟数,循环一次表示比较了一趟
{
for (int j = 0; j < scores.Length-1-i; j++)
{
if (scores[j] < scores[j + 1])
{
int temp = scores[j];
scores[j] = scores[j + 1];
scores[j + 1] = temp;
}
}
}
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine(scores[i]);
}
Console.ReadKey();
数组中的元素能按照我们预期的规律排序。
比较相邻的两个元素,如果第一个比第二个大,就交换它们两个。
对每一对相邻的元素进行同样的操作,从第一个到最后一个,比较完成后最后的数。
针对所有的元素重复以上的步骤,除了最后一个。
持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
从大到小排序,我们进行两两比较时用<,
反之,从小到大排序,我们进行两两比较时用>。
{
for(int j=0;j<num.length-1-i;j++)
{
if(num[j]<num[j+1])
{
int temp=num[j];
num[j]=num[j+1];
num[j+1]=temp;
}
}
}
例题:
int[] scores = { 19, 32, 43, 6, 71, 91, 10 }; //由大到小排序
for (int i = 0; i < scores.Length; i++)//控制比较的趟数,循环一次表示比较了一趟
{
for (int j = 0; j < scores.Length-1-i; j++)
{
if (scores[j] < scores[j + 1])
{
int temp = scores[j];
scores[j] = scores[j + 1];
scores[j + 1] = temp;
}
}
}
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine(scores[i]);
}
Console.ReadKey();