Bubble Sort Algorithm

A basic example of the bubble sort algorithm in Java.

Running a test file of 100000 randomly ordered integers through this algorithm takes about 15.8 seconds on my system. I will be using the same test file for comparison against other sorting algorithms.

Josh


/**
 * A very basic Bubble Sort class.
 * 
 * Sorting algorithm uses a common optimization to avoid 
 * resorting already sorted items at the end of the array.
 * 
 * This class will only sort an int[].
 * 
 * @author Joshua Weise
 */
public class BubbleSort {

	// array of numbers
	private int[] data;
	
	public BubbleSort(int[] data) {
		this.data = data;	
	}
	
	// bubble sort data
	public void sort() {	
		for (int i = data.length; i >= 0; i--) {
			for (int j = 0; j < i-1; j++) {	
				if (data[j] > data[j+1]) {
					swap(j, j+1);
				}
			}
		}		
	}
	
	// return data
	public int[] getData() {
		return data;
	}
	
	// swaps data in place at locations a and b in the array
	private void swap(int a, int b) {
		int z = data[a];
		data[a] = data[b];
		data[b] = z;	
	}
}

This entry was posted in Java, Sorting Algorithms. Bookmark the permalink.

Leave a Reply