改进冒泡排序算法

11年前

       冒泡排序(Bubble sort)是基于交换排序的一种算法。它是依次两两比较待排序元素,若为逆序(递增或递减)则进行交换。将待排序元素从左至右比较一遍称为一趟"冒泡"。每趟冒泡都将待排序列中的最大关键字交换到最后(或最前)位置。直到全部元素有序为止。若本次冒泡处理过程中,没有进行交换,说明序列已有序,则停止交换。这就是改进的冒泡算法的处理思想 。
public class BubbleSort   {   public void bubble(int [] a)   {    int i , j , t;    int flag = 0;//标记是否发生交换    int n = a.length;    for( i =0 ; i < n-1 ; i++)    {     for(j = n -1; j>i ; j--)     {      if(a[j-1]>a[j])      {       t = a[j-1];       a[j-1] = a[j];       a[j] = t ;       flag = 1;      }     }     System.out.print("第" + (i+1)+"遍: ");     for(j = 0 ; j < n ; j ++)     {      System.out.print(a[j]);     }     System.out.print("\n");     if(flag == 0)      break;     else      flag = 0;    }   }      public static void main(String[] args)    {    int [] b = {9,5,7,4,2,1,3};    BubbleSort bs = new BubbleSort();    bs.bubble(b);   }    }
输出: