Bubble Sort Algorithm

Below is the code to do Bubble Sorting in Java for integer values

public class BubbleSort {
  
    // logic to sort the elements
    public static void srtbubble(int array[]) {
        int n = array.length;
        int k;
        for (int m = n; m >= 0; m--) {
            for (int i = 0; i < n - 1; i++) { k = i + 1; if (array[i] > array[k]) {
                    swap(i, k, array);
                }
            }
            print(array);
        }
    }
  
    private static void swap(int i, int j, int[] array) {
  
        int temp;
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
  
    private static void print(int[] input) {
          
        for (int i = 0; i < input.length; i++) {
            System.out.print(input[i] + ", ");
        }
        System.out.println("\n");
    }
  
    public static void main(String[] args) {
        int[] input = { 14, 21, 19, 62, 233, 142, 134, 10, 41 };
        srtbubble(input);
    }
}


Output:

14, 19, 21, 62, 142, 134, 10, 41, 233, 

14, 19, 21, 62, 134, 10, 41, 142, 233, 

14, 19, 21, 62, 10, 41, 134, 142, 233, 

14, 19, 21, 10, 41, 62, 134, 142, 233, 

14, 19, 10, 21, 41, 62, 134, 142, 233, 

14, 10, 19, 21, 41, 62, 134, 142, 233, 

10, 14, 19, 21, 41, 62, 134, 142, 233, 

10, 14, 19, 21, 41, 62, 134, 142, 233, 

10, 14, 19, 21, 41, 62, 134, 142, 233, 

10, 14, 19, 21, 41, 62, 134, 142, 233,

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.