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;
                          }

                  }
              }
  }
}
4

1 回答 1

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]);
            ...............
            ...............
于 2012-04-03T12:09:34.757 回答