Bubble sort in Java
by hasan adil on 18/05/2010Bubblesort is one of the simplest sorting methods. It also very inefficient. Though in the best case when the elements are already sorted, then its run time is O(n). Otherwise it is O(n^2).
[sourcecode language="java"]
package com.labeltop.sort;
public class BubbleSort {
public void sort(Comparable[] comparables) {
int size = comparables.length;
// loop till swaps are being done
while (true) {
// reset it
boolean foundSwap = false;
// loop over values
int i = 0;
while (i < size) {
// don’t care about last value
if (i == size – 1)
break;
// check for swap i.e. c1 > c2
if (comparables[i].compareTo(comparables[i + 1]) > 0) {
Comparable temp = comparables[i];
comparables[i] = comparables[i + 1];
comparables[i + 1] = temp;
foundSwap = true;
}
// keep on…
i++;
}
// check if there were any swaps
if (!foundSwap)
break;
}
}
}
[/sourcecode]
There are 8,836 comments in this article: