Ad

Tuesday 31 March 2015

How to implement bubble sort algorithm in java

In this post we will see how to implement the bubble sort algorithm in java with a sample program.
Lets say there are N elements in the array to be sorted and the bubble sorting takes place by
  1.    Comparing  the adjacent elements in the array and swap its corresponding position if found greater.
  2.    Above step will be iterated upto the maximum of N -1 iteration until the array is fully sorted.
Below sample program will explain this in detail.

package test;

public class BubbleSortSample {

public static void main(String[] args) {
int[] arry = new int[] { 20, 3, 150, 5, 6, 78, 2, 123, 43, 45, 99, 1,
12 };
BubbleSortSample bubbleSort = new BubbleSortSample();
bubbleSort.sort(arry);
}

public void sort(int[] arry) {
printElements(arry);
int len = arry.length;
boolean isSwaped = false;
int temp = 0;
for (int i = 0; i < len; i++) {
isSwaped = false;
for (int j = 0; j < len - i - 1; j++) {
if (arry[j] > arry[j + 1]) {
temp = arry[j];
arry[j] = arry[j + 1];
arry[j + 1] = temp;
isSwaped = true;
}
}
printElements(arry);
if (!isSwaped) {
System.out.println("  Array has been fully sorted,hence rest of the iteration skipped");
break;
}
}
}

public void printElements(int[] arry) {
for (int i = 0; i < arry.length; i++) {
System.out.print(" " + arry[i]);
}
System.out.println();
}

}



When we run the above program,we will get this output

  20  3  150  5  6  78  2  123  43  45  99  1  12
  3  20  5  6  78  2  123  43  45  99  1  12  150
  3  5  6  20  2  78  43  45  99  1  12  123  150
  3  5  6  2  20  43  45  78  1  12  99  123  150
  3  5  2  6  20  43  45  1  12  78  99  123  150
  3  2  5  6  20  43  1  12  45  78  99  123  150
  2  3  5  6  20  1  12  43  45  78  99  123  150
  2  3  5  6  1  12  20  43  45  78  99  123  150
  2  3  5  1  6  12  20  43  45  78  99  123  150
  2  3  1  5  6  12  20  43  45  78  99  123  150
  2  1  3  5  6  12  20  43  45  78  99  123  150
  1  2  3  5  6  12  20  43  45  78  99  123  150
  1  2  3  5  6  12  20  43  45  78  99  123  150
  Array has been fully sorted,hence rest of the iteration skipped

Above output will show the array elements position at the end of each iteration and how the elements in the arrays were swapped.

No comments:

Post a Comment