【问题标题】:Printing the array through each pass (Bubble Sort)通过每次传递打印数组(冒泡排序)
【发布时间】:2012-04-03 12:07:27
【问题描述】:

我正在寻找一种在每次通过后按原样打印数组的方法。这是我到目前为止的排序代码。它是冒泡排序算法的基本实现,打印出数组的原始状态和排序状态

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

                  }
              }
  }
}

【问题讨论】:

    标签: java sorting bubble-sort


    【解决方案1】:

    在排序的外循环内添加一个新的 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]);
                ...............
                ...............
    

    【讨论】:

    猜你喜欢
    • 2016-06-28
    • 1970-01-01
    • 2013-10-09
    • 2022-01-26
    • 2017-05-29
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    • 2013-09-28
    相关资源
    最近更新 更多