Java – Bubble Sort Array Example

[code lang=”java”]import java.util.Arrays;

/**
* Algorithm
*
* 1] Compare each pair of adjacent elements from 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 {

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);
}

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));
}

}[/code]