Sort array using Bubble sort - Java Program

Q. Write a program to sort the array using bubble sort technique.

Answer:

Bubble sort:
It is a simple sorting technique that work by repeatedly swapping the adjacent elements if they are in wrong order.

Using of Bubble sort compares all the element one by one and sort them based on their value.  

BubbleSort.java

class BubbleSort
{
    void bubbleSort(int arr[])
    {
        int n = arr.length;
        for (int i = 0; i < n-1; i++)
            for (int j = 0; j < n-i-1; j++)
                if (arr[j] > arr[j+1])
                {
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
    }
    void display(int arr[])
    {
        int n = arr.length;
        for (int i=0; i<n; ++i)
            System.out.print(arr[i] + " ");
        System.out.println();
    }

    public static void main(String args[])
    {
        BubbleSort obj = new BubbleSort();
        int arr[] = {32, 34, 15, 72, 12, 83, 90, 43, 62};
        System.out.println("Given array:");
        obj.display(arr);
        obj.bubbleSort(arr);
        System.out.println("\nSorted array:");
        obj.display(arr);
    }
}


Output:

bubble sort