Bubble sort is an easy algorithm from the development point of view. It is very straight forward. The running time of the algorithm depends on the number of the elements and their initial order. The logic is simple, compare two adjacent elements and swap them if needed. Iterate till the end of the array. To improve performance of the algorithm lets create a flag ‘swapped’ and loop every other time to -1 last element ¬†which is supposed to be already the largest or the smallest.

Java code snippet

public static int[] bubleSort(int[] array) {		
	boolean swapped = true;
	int i = 0;				
	while(swapped) {
		i++;
		swapped = false;
		for(int j = 0; j < array.length - i; j++) { //end every loop with -1 last element			
			if(array[j] > array[j + 1]) {
				swap(array, j, j + 1);					
				swapped = true;
			}				
		}
	}

	return array;
}
public static void swap (int[] array, int i, int j)
{
    int temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

Complexity analysis

Best: O(n)

Worst: O(n^2)

Dima Svirid

Software architect, JAVA, Spring, Hibernate, AngularJs, Backbone, MongoDB, Oracle. CTO and Co-Founder of Homeadnet.com

More Posts

Follow Me:

Tagged with: