This example shows how to sort an Integer Array using Bubble Sort algorithm in Java.
Steps in Bubble Sort Algorithm as follows-
Step-1: Compare each pair of adjacent elements from beginning of an array and, if they are in reversed order, swap them.
Step-2: If at least one swap has been done, repeat step 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.util.Arrays; 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)); } } |