Bubble Sorting in Java

Bubble Sorting is an algorithm in which we are comparing first two values and put the larger one at higher index. Then we take next two values compare these values and place larger value at higher index. This process do iteratively until the largest value is not reached at last index. Then start again from zero index up to n-1 index. The algorithm follows the same steps iteratively unlit elements are not sorted

Working of bubble sort algorithm:


Say we have an array unsorted A[0],A[1],A[2]................ A[n-1] and A[n] as input. Then the following steps are followed by bubble sort algorithm to sort the values of an array.
1.Compare A[0] and A[1] .
2.If A[0]>A[1] then Swap A[0] and A[1].
3.Take next A[1] and A[2].
4.Comapre these values.
5.If A[1]>[2] then swap A[1] and A[2]
...............................................................
................................................................
at last compare A[n-1] and A[n]. If A[n-1]>A[n] then swap A[n-1] and A[n].
As we see the highest value is reached at nth position.
At next iteration leave nth value.
Then apply the same steps repeatedly on A[0],A[1],A[2]................ A[n-1] elements repeatedly until the values of array is sorted.

In our example we are taking the following array values

5 4 3 1 2
The basic steps followed by algorithm :
In the first step compare first two values 5 and 4.
5 4 3 1 2
As 5 > 4 then we have to swap these values
Then the new sequence will be
4 5 3 1 2
In next step take next two values 5and 3
4 5 3 2 1
Compare these two values .
As 5 > 3 then we have to swap these values.
Then the new sequence will be
4 3 5 2 1
In next step take next two values 5 and 2
4 3 5 2 1
Compare these two values .
As 5 > 2 then we have to swap these values.
Then the new sequence will be
4 3 2 1 5
We have to follow similar steps up to end of array....
4 3 2 1 5
4 3 2 1 5
3 4 2 1 5
3 2 4 1 5
3 2 1 4 5
3 2 1 4 5
2 3 1 4 5
............
............
1 2 3 4 5

Bubble Sort


When you run the program, the output will be:

Before Bubble Sort
85  23  83  71  49  
After Bubble Sort
23  49  71  83  85  

Previous Post Next Post