Wednesday, December 7, 2011

Algorithms: Bubble Sort in Java



Bubble sort, also known as sinking sort, is 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.
Although the algorithm is simple, it is not efficient for sorting large lists; other algorithms are better.

Worst case performance О(n2)
Best case performance О(n)
Average case performance О(n2)

where n is the number of items being sorted

Formula of Bubble Sort should be n(n-1). For 8 elements there should be 56 possible comparison


public class BubbleSort {

                public static void main(String args[]){
               
                                int[] array={5,3,8,4,6};
                                printArray(array);
                                int comparison=0;
                                for(int j=0;j<array.length;j++){
                                               
                                for(int i=0;i<array.length-1;i++){
                                                int a=array[i];
                                                int b=array[i+1];
                                                comparison++;
                                                if(a>b){
                                                                array[i]=b;
                                                                array[i+1]=a;
                                                }
                                               
                                }
                                }
                                System.out.println();
                                printArray(array);
                                System.out.println();
                                System.out.println(comparison);
                }
               
                public static void printArray(int[] array){
                                for(int i:array){
                                                System.out.print(i+",");
                                }
                }
}


WikiPedia has very good article about Sorting Algorithms


No comments:

Post a Comment