笨鸟也来用冒泡

编程入门 行业动态 更新时间:2024-10-26 16:24:52

笨鸟也<a href=https://www.elefans.com/category/jswz/34/1692297.html style=来用冒泡"/>

笨鸟也来用冒泡

 

 

冒泡算法的基本原理就是对一个序列,循环进行比较,最小的在最上面,外层的循环为数组的长度,内层循环为需要比较的次数,

如只有两二个数我们外层循环两次,内层循环只需要比较一次

如定义数组如下:

  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

更多推荐

笨鸟也来用冒泡

本文发布于:2024-02-26 00:05:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1700703.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:来用   笨鸟也

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!