Thursday, 28 April 2016

How to do Bubble sort in Java ?



Bubble sort - Complexity O(n^2)

Algorithm
  • Repeat below steps n times
    • Compare array[0] & array[1]
      • If array[0] > array [1] swap it
    • Compare array[1] & array[2]
      • If array[1] > array[2] swap it
    • ....



Java code
int n = array.length;
int temp = 0;


for (int i=0; i < n; i++){   // n passes
   for (int j=1; j < (n-i); j++){
         if (array[j-1] > array[j]){
              // swap
              temp = array[j-1];
              array[j-1] = array[j];
              array[j] = temp;
         }
   }

}

Complexity : O(n2)


Execution during all n passes
4, 2, 9, 6, 23, 12, 34,  0,  1


2, 4, 6, 9, 12, 23, 0, 1, 34, 2, 4, 6, 9, 12, 0, 1, 23, 34, 2, 4, 6, 9, 0, 1, 12, 23, 34, 2, 4, 6, 0, 1, 9, 12, 23, 34, 2, 4, 0, 1, 6, 9, 12, 23, 34, 2, 0, 1, 4, 6, 9, 12, 23, 34, 0, 1, 2, 4, 6, 9, 12, 23, 34, 0, 1, 2, 4, 6, 9, 12, 23, 34, 0, 1, 2, 4, 6, 9, 12, 23, 34, 0, 1, 2, 4, 6, 9, 12, 23, 34, - See more at: http://www.java2novice.com/java-interview-programs/bubble-sort/#sthash.DV55ntRH.dpuf
2, 4, 6, 9, 12, 23,  0,  1, 34
2, 4, 6, 9, 12,  0,  1, 23, 34
2, 4, 6, 9,  0,  1, 12, 23, 34
2, 4, 6, 0,  1,  9, 12, 23, 34
2, 4, 0, 1,  6,  9, 12, 23, 34
2, 0, 1, 4,  6,  9, 12, 23, 34
0, 1, 2, 4,  6,  9, 12, 23, 34
0, 1, 2, 4,  6,  9, 12, 23, 34
0, 1, 2, 4,  6,  9, 12, 23, 34
0, 1, 2, 4,  6,  9, 12, 23, 34

Highlighted are swapped during each pass.


4, 2, 9, 6, 23, 12, 34, 0, 1
4, 2, 9, 6, 23, 12, 34, 0, 1

No comments:

Post a Comment

Note: only a member of this blog may post a comment.