冒泡排序
本质:较小的值会逐渐冒泡至数组的顶端,同时较大的数会下沉到低端。
算法如下:
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 ] =