Java: BubbleSort

The bubblesort algorithm is one of the slowest sorting algorithms around as it’s performance is O(n²). As a result of this the algorithm is barely ever used in any real life applications, however, even though the algorithm will always stay rather slow, it can be tweaked to improve the code’s performance.

The implementation of the algorithm you see below has been optimized in various ways and it also makes use of the property that all items in an array of numbers that come after the last index that was sorted in a run through the array by the algorithm are already sorted.

public static void bubbleSort(int[] ia) {
	int l = ia.length, i = l;
	if (l == 1)
	while (i != 0) {
		int last = 0;
		for (int j = 1; j != i; j++)
			if (ia[j - 1] > ia[j]) {
				int t = ia[j];
				ia[j] = ia[j - 1];
				ia[j - 1] = t;
				last = j;
		i = last;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.