Sunday, May 13, 2012

Bubble Sort in Java


public class BubbleSort {
    public static void main(String[] args){
       int[] array = {1,2,3,4,5};
       new BubbleSort().bubbleSort(array);

       for(int i=0; i < array.length  ; i++)
           System.out.println(array[i]);        
    }

    public void bubbleSort(int[] array){
       int length = array.length;
       int count = 0; //counts if no swapping is done

       for(int i = 0 ; i <= length-2 ; i++){
           count = 0;
           for(int j = 0 ; j <= length-i-2 ; j++){
                 if(array[j] > array[j+1]){
                     int temp = array[j];
                     array[j] = array[j+1];
                     array[j+1] = temp;
                     count ++ ;
                   }                      
               }
            if(count == 0){  // This if is not there in actual algorithm. If there are no swaps in the pass that means the array is sorted
                  System.out.println("broke on i = " + i);
                  break;                 
            }
         }
    }  
}

No comments:

Post a Comment