General
This article will show you how the bubble sort algorithm works and the way it is implemented in Java. Let’s start with an example array of five given integer values like this:
[ 12 7 5 88 42 ]
The bubble sort algorithm works by iterating over that array, comparing all pairs of integers and swapping their indices if the left one is greater than the right one. Take a look on what happens to our example array:
1st iteration
[ 12 7 5 88 42 ] swap [ 7 12 5 88 42 ]
[ 7 12 5 88 42 ] swap [ 7 5 12 88 42 ]
[ 7 5 12 88 42 ] swap [ 7 5 12 88 42 ]
[ 7 5 12 88 42 ] swap [ 7 5 12 42 88 ]
As long as there are swapping actions in an iteration, the exit condition of bubble sort is not satisfied.
2nd iteration
[ 7 5 12 42 88 ] swap [ 5 7 12 42 88 ]
[ 5 7 12 42 88 ] swap [ 5 7 12 42 88 ]
[ 5 7 12 42 88 ] swap [ 5 7 12 42 88 ]
[ 5 7 12 42 88 ] swap [ 5 7 12 42 88 ]
3rd iteration
[ 5 7 12 42 88 ] swap [ 5 7 12 42 88 ]
[ 5 7 12 42 88 ] swap [ 5 7 12 42 88 ]
[ 5 7 12 42 88 ] swap [ 5 7 12 42 88 ]
[ 5 7 12 42 88 ] swap [ 5 7 12 42 88 ]
And this is the sorted array:
[ 5 7 12 42 88 ]
Wuhuuu! Everything looks great. We can now take a look at the Java implementation:
Bubble Sort in Java
private int[] bubbleSort(int[] arr) {
boolean unsorted = true;
while (unsorted) {
unsorted = false;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
int tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
unsorted = true;
}
}
}
return arr;
}
That’s it!
I’m looking forward to describe and explain some other algorithms on binarycoded.com soon.