Sunday, May 13, 2012

Selection Sort in Java


public class SelectionSort {
    public static void main(String[] args) {
       int[] array = {6,7,3,8,1,2,3,4,5};
       new SelectionSort().selectionSort(array);

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

    public void selectionSort(int[] array ){
       int min = 0;
       int length = array.length;

       for (int i = 0; i <= length - 2; i++){
           min = i;
           for(int j = i+1 ; j <= length - 1 ; j++){
                 if(array[min] > array[j]){
                    min = j;
                 }
       }

            if(min != i){     // This if condition is not there in original algorithm. It helps unnecessary swapping of same value in to same location again (min = i) 
                int temp = array[i];
                array[i] = array[min];
                array[min] = temp;
            }
        }
      }
}

No comments:

Post a Comment