Java Program for Bubble Sort

Bubble Sort is a very basic and simple sorting technique which works by repeatedly stepping throughout the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed which indicates that the list is sorted.

Java Program for Bubble Sort

public class BubbleSort {

   public static void main(String args[]) {

     int array[] = {547, 23, 523, 2378, 243, 7854, 14, 23, 310};

     System.out.println("Unsorted array: ");
     printArray(array);


     for (int i=0; i<array.length-1; i++) {
       for (int j=0; j<array.length-1; j++) {

         if (array[j] > array[j+1]) {
           int t = array[j];
           array[j] = array[j+1];
           array[j+1] = t;
         }
       }
       System.out.println("End of pass "+ (i+1));
       printArray(array);
     }

     System.out.println("Sorted array: ");
     printArray(array);
   }

   private static void printArray(int a[]) {
     for (int i=0; i<a.length; i++)
       System.out.print(a[i]+"  ");
     System.out.println("\n");
   }
}

Output of Bubble Sort Java Program

0 comments:

Post a Comment