来用冒泡"/>
笨鸟也来用冒泡
冒泡算法的基本原理就是对一个序列,循环进行比较,最小的在最上面,外层的循环为数组的长度,内层循环为需要比较的次数,
如只有两二个数我们外层循环两次,内层循环只需要比较一次
如定义数组如下:
int [] array = new int [] { 1 , 4 , 5 , 7 , 3 , 1 , 23 , 43 , 4 , 6 , 8 };数组长度为n,我们只需要比较n-1次
因此外层循环应该写为:我们先定义一个int 数组
外层循环为:
for ( int i = 0 ; i < array.Length - 1 ; i ++ ){
}
当外层循环到i时,0到i其实已经是有顺序的了,因此内层循环只需要控制在i就可以了
由下到上循环:
for ( int j = array.Length - 1 ; j > i; j -- ){
}
在内层循环做比较:
if (array[j] < array[j - 1 ]){
int temp;
temp = array[j];
array[j] = array[j - 1 ];
array[j - 1 ] = temp;
}
所有代码:
代码 private static void BubbleSort()
{
int [] array = new int [] { 1 , 4 , 5 , 7 , 3 , 1 , 23 , 43 , 4 , 6 , 8 };
for ( int i = 0 ; i < array.Length - 1 ; i ++ )
{
for ( int j = array.Length - 1 ; j > i; j -- )
{
if (array[j] < array[j - 1 ])
{
int temp;
temp = array[j];
array[j] = array[j - 1 ];
array[j - 1 ] = temp;
Console.WriteLine( " {0}<-->{1} " , array[j - 1 ].ToString(), array[j].ToString());
}
}
}
AlgorithmHelper < int > .PrintArray < int > (array);
Console.ReadKey();
}
转载于:.html
更多推荐
笨鸟也来用冒泡
发布评论