Sunday, April 5, 2015

BubbleSort



public void bubbleSort(int[] a) {
         System.out.println("Input Array:");
         for (int i = 0; i < a.length; i++) {
                  System.out.print("  "+a[i]);
         }
         System.out.println();
         for (int p = 0; p < a.length; p++) {
                  for (int i = 0, j = 1; i < a.length && j < a.length; i++, j++) {
                           System.out.print("comparing "+a[i]+" & "+a[j] +"   ");
                            if(a[i] > a[j]){
                                     int tmp = a[i];
                                    a[i] = a[j];
                                    a[j] = tmp;
                           }
         
                           for (int k = 0; k < a.length; k++) {
                                  System.out.print("  "+a[k]);
                           }
                           System.out.println();
                  }
         }
         
         System.out.println("Array is sorted:");
         for (int i = 0; i < a.length; i++) {
                  System.out.print("  "+a[i]);
         }

}


OutPut:
Input Array:
  3  2  5  7  1  12
comparing 3 & 2     2  3  5  7  1  12
comparing 3 & 5     2  3  5  7  1  12
comparing 5 & 7     2  3  5  7  1  12
comparing 7 & 1     2  3  5  1  7  12
comparing 7 & 12     2  3  5  1  7  12
comparing 2 & 3     2  3  5  1  7  12
comparing 3 & 5     2  3  5  1  7  12
comparing 5 & 1     2  3  1  5  7  12
comparing 5 & 7     2  3  1  5  7  12
comparing 7 & 12     2  3  1  5  7  12
comparing 2 & 3     2  3  1  5  7  12
comparing 3 & 1     2  1  3  5  7  12
comparing 3 & 5     2  1  3  5  7  12
comparing 5 & 7     2  1  3  5  7  12
comparing 7 & 12     2  1  3  5  7  12
comparing 2 & 1     1  2  3  5  7  12
comparing 2 & 3     1  2  3  5  7  12
comparing 3 & 5     1  2  3  5  7  12
comparing 5 & 7     1  2  3  5  7  12
comparing 7 & 12     1  2  3  5  7  12
comparing 1 & 2     1  2  3  5  7  12
comparing 2 & 3     1  2  3  5  7  12
comparing 3 & 5     1  2  3  5  7  12
comparing 5 & 7     1  2  3  5  7  12
comparing 7 & 12     1  2  3  5  7  12
comparing 1 & 2     1  2  3  5  7  12
comparing 2 & 3     1  2  3  5  7  12
comparing 3 & 5     1  2  3  5  7  12
comparing 5 & 7     1  2  3  5  7  12
comparing 7 & 12     1  2  3  5  7  12
Array is sorted:
  1  2  3  5  7  12

No comments:

Post a Comment