Selection Sort Program in Java

Selection Sort is a sorting algorithm where an array is repeatedly finding the minimum  number or element from unsorted part(subarray) and putting it into sorted part(subarray).
Selection Sort maintains two subarray for sorting:
  • First subarray is used for sorted elements and
  • Second subarray for unsorted elements and vice versa.

Lets see the Selection Sort Program in Java:


public class SelectionSortExample {  
    
    public static void SelectionSort(int arr[]){
        
        int index;
        
        for(int i=0; i<arr.length-1; i++){
            
            index = i;
            
            for(int j=i+1; j<arr.length; j++){
                
                if(arr[j]<arr[index]){
                    index = j;
                }
                
            }
            
            int smallerNum = arr[index];
            arr[index]=arr[i];
            arr[i]=smallerNum;
            
        }
        
    }

    public static void main(String a[]){  
        
        int[] arr = {8,5,2,6,9,3,1,4,0,7};  
        
        System.out.println("Before Selection Sort");  
        for(int i: arr){
            System.out.print(i+"  ");
        }
        
        SelectionSort(arr);
        
        System.out.println("\n\nAfter Selection Sort");  
        for(int i: arr){
            System.out.print(i+"  ");
        }
    }  
    
}

Comments