Home > Java, Java Misc, Java Sorting > Bubble sort in Java

Bubble sort in Java

Bubblesort 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).

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)

				// 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...

			// check if there were any swaps
			if (!foundSwap)
Categories: Java, Java Misc, Java Sorting
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: