2012-04-03 45 views
1

即时通讯寻找一种方法来打印每个通过后的数组。这是迄今为止我的排序代码。其基本实施打印出阵列的原始状态和排序状态通过每次通过打印阵列(气泡排序)

public class bubbleSortTest 
{ 
    public static void main(String a[]) 
    { 
     int i; 
     int array[] = {90, 8, 7, 56, 123, 235, 9, 1, 653}; 

     System.out.println("Values Before the sort:\n"); 

     for(i = 0; i < array.length; i++) 
      System.out.print(array[i]+" "); 
      System.out.println(); 
      bubble_srt(array, array.length); 
      System.out.print("Values after the sort:\n"); 
     for(i = 0; i <array.length; i++) 
     System.out.print(array[i]+" "); 
     System.out.println(); 
     System.out.println("PAUSE"); 
    } 

    public static void bubble_srt(int a[], int n) 
    { 
     int i, j,t=0; 
      for(i = 0; i < n; i++) 
       { 
       for(j = 1; j < (n-i); j++) 
        { 
         if(a[j-1] > a[j]) 
          { 
           t = a[j-1]; 
           a[j-1]=a[j]; 
           a[j]=t; 
          } 

        } 
       } 
    } 
} 

回答

0

冒泡排序算法的添加新的for循环排序每次通过后打印的值的外环内。

for(i = 0; i < n; i++) 
     { 
     System.out.print(" After "+(i+1)+"st pass: "); 
     for(k=0;k<n;k++) 
      System.out.print(" "+a[k]); 
      ............... 
      ............... 
+0

如果在内部循环中没有“交换”,则表示该列表已排序。所以你可以停止排序过程。请参阅这里了解各种排序算法:http://www.sorting-algorithms.com/bubble-sort – 2012-04-03 12:37:35