您的位置:首页 > 其它

数组排序——冒泡排序

2013-06-25 12:17 183 查看
冒泡排序

本质:较小的值会逐渐冒泡至数组的顶端,同时较大的数会下沉到低端。

算法如下:

1、比较相邻的两个元素,如果第一个比第二个大,则交换位置。

2、针对所有元素重复以上的步骤,除了最后一个。

3、重复以上步骤遍历数组,直到没有任何一个数字需要比较。

时间复杂度为O(n^2) 比较慢

稳定排序算法

程序如下

// Bubble sort

import java.io.IOException;

public class BubbleSort {
public static void main( String args[] ) throws IOException
{
int a[ ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int temp;

// print the original array
System.out.println( "The original array: " );

for ( int i = 0; i < a.length; i++ )
System.out.print( " " + a[ i ] + " " );

// sort the array
for ( int k = 0; k < a.length; k++)
{
for ( int j = 0; j < a.length - 1; j++ )
{
if ( a[ j + 1 ] < a[ j ] )
{
temp = a[ j ];
a[ j ] = a[ j + 1 ];
a[ j + 1 ] = temp;
}
}
}

// print the sorted array
System.out.println( "\nThe sorted array: " );

for ( int i = 0; i < a.length; i++ )
System.out.print( " " + a[ i ] + " " );
}
}
结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: