Pages

Tuesday, 22 April 2014

Bubble Sort Implementation in Java

Bubble Sort

A simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
Bubble Sort Example - GIF Format

Bubble Sort in Java

 public class BubbleSort {  
      public static void bubbleSort(int[] array) {  
           // check for empty or null array
           if (array ==null || array.length==0) {  
                return;
           }
           boolean flag = true;  
           while (flag) {  
                flag = false;  
                for (int i = 0; i < array.length - 1; i++) {  
                     if (array[i] > array[i + 1]) {  
                     int temp = array[i];  
                     array[i] = array[i + 1];  
                     array[i + 1] = temp;  
                     flag = true;  
                }  
           }  
      }  
      public static void main(String[] args) {  
           int[] numbers = { 84, 69, 76, 86, 94, 91 };  
           print("Before: ", numbers);  
           bubbleSort(numbers);  
           print("After: ", numbers);  
      }  
      public static void print(String label, int[] numbers) {  
           System.out.print(label + ": ");  
           for (int i : numbers) {  
                System.out.print(i + " ");  
           }  
           System.out.println();  
      }  
 }  

Complexity Analysis


Bubble Sort Complexity
Case Complexity
Worst case performance O(n^2)
Best case performance O(n)
Average case performance O(n^2)

Looking at worst case performance, Bubble sort is not a practical sorting algorithm when n is large.
The only significant advantage that bubble sort has over most other implementations, even quicksort, but not insertion sort, is that the ability to detect that the list is sorted is efficiently built into the algorithm. When the list is already sorted (best-case), the complexity of bubble sort is only O(n).

References

No comments:

Post a Comment