Bubble sort is a simple sorting algorithm that repeatedly steps through the list should be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. Do you know why its called as Bubble sort because The smaller value bubbles up to the top of the list, while the larger value sinks to the bottom.
Please find the complete source code from my tech blog - http://www.algonuts.info/java---how-to-create-a-bubble-sort.html
package info.algonuts;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
class BubbleSortCompute {
static List <Integer> intList = new ArrayList <Integer>();
public static void add(List <Integer> temp) {
intList.clear();
Iterator<Integer> ptr = temp.iterator();
while(ptr.hasNext()) {
intList.add(ptr.next());
}
}
public static void sort() {
System.out.println("Before Bubble Sort:");
Iterator<Integer> ptr = intList.iterator();
while(ptr.hasNext()) {
System.out.print(ptr.next()+" ");
}
System.out.println("\n\nAfter Bubble Sort:");
compute();
ptr = intList.iterator();
while(ptr.hasNext()) {
System.out.print(ptr.next()+" ");
}
}
private static void compute() {
int temp;
int intListSize = intList.size();
for(int outerCounter = 0;outerCounter < intListSize; outerCounter++) {
for(int interCounter = 0;interCounter < intListSize - outerCounter - 1; interCounter++) {
if(intList.get(interCounter) >= intList.get(interCounter+1)) {
temp = intList.get(interCounter+1);
intList.set(interCounter+1, intList.get(interCounter));
intList.set(interCounter, temp);
}
}
}
}
}
public class BubbleSort {
//Entry Point
public static void main(String[] args) {
List <Integer> intList = new ArrayList <Integer>(Arrays.asList(50,2,5,78,90,20,4,6,98,1));
BubbleSortCompute.add(intList);
BubbleSortCompute.sort();
}
}