{
int[] arr ={2,5,8,9,1,57,8,5877,5,58,56,3,557,7};
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr.Length - i-1; j++)
{
if (arr[j] > arr[j+1])
{
int m=arr[j];
arr[j] = arr[j+1];
arr[j+1] = m;
}
}
}
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i].ToString());
}
Console.ReadKey();
}
现在来讲一下程序运行过程:
2,5,8,1,9,8,57,5,58,56,3,557,7,5877,| i的第一次循环
2,5,1,8,8,9,5,57,56,3,58,7,557,5877,| 依次
2,1,5,8,8,5,9,56,3,57,7,58,557,5877,|
1,2,5,8,5,8,9,3,56,7,57,58,557,5877,|
1,2,5,5,8,8,3,9,7,56,57,58,557,5877,|
1,2,5,5,8,3,8,7,9,56,57,58,557,5877,|
1,2,5,5,3,8,7,8,9,56,57,58,557,5877,|
1,2,5,3,5,7,8,8,9,56,57,58,557,5877,|
1,2,3,5,5,7,8,8,9,56,57,58,557,5877,|
1,2,3,5,5,7,8,8,9,56,57,58,557,5877,|
1,2,3,5,5,7,8,8,9,56,57,58,557,5877,|
1,2,3,5,5,7,8,8,9,56,57,58,557,5877,|
1,2,3,5,5,7,8,8,9,56,57,58,557,5877,|
1,2,3,5,5,7,8,8,9,56,57,58,557,5877,|
第一次循环的时候:首先arr[0]跟arr[1]比较 ,如果arr[0]大于arr[1]那么原来 arr[0]的值和arr[1]的值互换,再次内循环
arr[1]此时值不变=5 ,arr[2]=8 这两个比较 arr[1]<arr[8]那么不变动, 然后再比较arr[2]=8和arr[3]=1 ,arr[2]>arr[3],值互换,在循环 arr[3]此时值为=8,arr[4]=9, 一次比较
因此第一次循环之后 最后一值肯定是最大的那个值
1,2,5,8,5,8,9,3,56,7,57,58,557,5877,|
此时最大值已经得到,因此下次循环只用比较最大值之前那几位数字!
所以
for (int j = 0; j < arr.Length - i-1; j++)
需要这样比较!i=0的时候 需要全部比较
i=1的时候只要比较13个数字就可以了(因为最后一个已经是最大的那个值了)
这样就是把最大的那个依次往后排(就像泡泡一样一个一个浮出来)
完整代码:
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] arr ={2,5,8,9,1,57,8,5877,5,58,56,3,557,7};
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr.Length - i-1; j++)
{
if (arr[j] > arr[j+1])
{
int m=arr[j];
arr[j] = arr[j+1];
arr[j+1] = m;
}
}
//注意这里只是用来 将每次循环的结果显示出来
//正式里面不用写这个
for (int l = 0; l < arr.Length; l++)
{
Console.Write(arr[l].ToString() + ",");
}
Console.WriteLine("|");
Console.ReadKey();
//到这里
}
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i].ToString());
}
Console.ReadKey();
}
}
}