A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

write a program to sort an array using bubble sort in java and define Sorting a One-Dimensional Array using a Bubble Sort

Sorting a One-Dimensional Array using a Bubble Sort


/*

Starting:
    9 3 5 6 2
        Use all 5 elements:
        9 > 3, so swap: 3 9 5 6 2
        9 > 5, so swap: 3 5 9 6 2
        9 > 6, so swap: 3 5 6 9 2
        9 > 2, so swap: 3 5 6 2 9
    3 5 6 2 [9]
        Now use first 4 elements:
        3 not > 5, no swap
        5 not > 6, no swap
        6 > 2, so swap: 3 5 2 6 [9]
    3 5 2 [6 9]
        3 elements:
        3 not > 5, no swap
        5 > 2, so swap: 3 2 5 [6 9]
    3 2 [5 6 9]
        2 elements:
        3 > 2, so swap: 2 3 [5 6 9]
    2 [3 5 6 9]
        1 element:
        nothing to do
    [2 3 5 6 9]
This method is called a Bubble Sort.

*/

public class BubbleSort
{
    public static void main(String args[])
    {
        int a[]={2,8,9,3,4,5};
        int temp;
        int i,j;
        for(i=0; i<=5; i++)
        {
            for(j=i+1; j<=5; j++)
            {
                if(a[i] > a[j])
                {
                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                   
                }
            }
            System.out.println(a[i]);
        }
    }
}



Sample output:



LEARN TUTORIALS

.

.