Posted By

rnavanee on 09/16/13

My Bubble Sort

/ Published in: Java

Bubble Sort - Algorithm

``````1. Compare each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them.
2. If at least one swap has been done, repeat step 1.
``````

`import java.util.Arrays;  /** * Ref: http://www.algolist.net/Algorithms/Sorting/Bubble_sort *  * Algorithm * 	1. Compare each pair of adjacent elements from the beginning  * 	of an array and, if they are in reversed order, swap them. * 	2. If at least one swap has been done, repeat step 1. *  * */public class MyBubbleSort { 	public static void main(String[] args) {		int[] data = {5,1,12,-5,16};		System.out.println(Arrays.toString(data));		new MyBubbleSort().sortData(data);		System.out.println(Arrays.toString(data));	} 	private void sortData(int[] data) {		boolean swapDone = false;		do {			swapDone = false;			for (int i=0; i<data.length-1; i++) {				if (data[i]>data[i+1]) {					swapDone = true;					int tmp = data[i];					data[i] = data[i+1];					data[i+1] = tmp;				}			}		} while (swapDone==true);	}}`