/*****************************************************************************/
/*                                                                           */
/*                          Bubble Sort Program                              */
/*                                                                           */
/*                       March 1998, Toshimi Minoura                         */
/*                                                                           */
/*****************************************************************************/

// Numbers in array data[] are sorted by bubble sort.
// Array elements data[i] such that i <= ceilingIdx are sorted.
// Elements data[i-1] and data[i] are compared, and they are exchanged
// if data[i-1] > data[i].

class BubbleSort {
  // data[] provides data to be sorted
  private int data[] = { 17, 10, 8, 13, 15, 4, 6, 20, 15, 18 };

  private int ceilingIdx;       // index of last sorted element
  private int currentIdx;       // index to current slot 


  public void dataPrint() {           // print array content
     System.out.print("daraPrint(): ceilingIdx = " + ceilingIdx + ", data = ");
      for (int i = 0; i < data.length; i++) {
        System.out.print(data[i]);    // print every value in data[]
        if (i < data.length - 1) System.out.print(", ");
      };
      System.out.println("");
   }

  public void sort() {
    System.out.println("BubbleSort.sort() entered");

    dataPrint();
    ceilingIdx = -1;
    for ( ; ceilingIdx < data.length - 1; ) {
      currentIdx = data.length - 1;
      for ( ; currentIdx > ceilingIdx + 1; currentIdx--) {
        System.out.println("Values " + data[currentIdx] + " and " +
                                data[currentIdx - 1] + " are compared.");
        if (data[currentIdx] < data[currentIdx - 1]) { // out of order?
          int temp = data[currentIdx];
          data[currentIdx] = data[currentIdx - 1];     // sawp values
          data[currentIdx - 1] = temp;
          System.out.println("Values " + data[currentIdx - 1] + " and " +
                                data[currentIdx] + " were exchanged.");
          dataPrint();
        } else {          // no, continue to move up for insertion point
          System.out.println("Values " + data[currentIdx - 1] + " and " +
                                data[currentIdx] + " are right order.");
          dataPrint();
        }
      }
      ceilingIdx++;       // additional element got sorted
      dataPrint();
      System.out.println("Bubbling to slot " + ceilingIdx + " done.");
    }
    System.out.println("sort() completed");
  }  

  public static void main(String argv[]) {
    System.out.println("BubbleSort.main() entered");
    BubbleSort bubbleSort = new BubbleSort();
    bubbleSort.sort();
    System.out.println("main() completed");
  }  
}

