Home » Java » Selection Sort Algorithm with full code – java

Selection Sort Algorithm with full code – java

In this tutorial, we are going to learn how to implement selection sort in java. Selection sort is a very popular and very useful algorithm in programming.

Here, I will create a class “Sotrs” and a method “selectionSort”. The method declared as a static method because we can call static methods directly without creating an instance of the corresponding class.

Also, there is an integer array called “arr1” with 4,9,5,1,0 elements. There are two for loop in the main method. The for loop number one will print the elements of the array before the sorting and the for loop number two will print the elements in the array two after the sorting.

In line 1, the selectionSort method will be called with a parameter. Here the parameter is our array.

Now we look at steps in the selectionSort method. The following figure explains the basic steps of the selection sort algorithm.

Selection sort steps
Selection sort steps

Here, I will declare a variable called index. the index will be assigned the current value of the “i” in the outer for loop. Out for loop runs according to the length of the array. In the inner for loop, if the value of the selected element (selection) is greater than the value of the current element, the values of each element will be swapped with the help of “smallerNumber ” variable.

public class Sorts {
    public static void main(String[] args) {

        int[] arr1 = {4,9,5,1,0}; 
   
        System.out.println("Before Insertion Sort");  
        
        //For loop number one
        for(int i:arr1){    
            System.out.print(i+" ");    
        }  
  
        System.out.println();    
           
        //sorting array using selection sort
        selectionSort(arr1);   // Line 1 
       
        // For loop number two
        System.out.println("After selection Sort");    
        for(int i:arr1){    
            System.out.print(i+" ");    
        } 
    }
    
    public static void selectionSort(int[] arr){  
        for (int i = 0; i < arr.length - 1; i++)  
        {  
            int index = i;  
            for (int j = i + 1; j < arr.length; j++){  
                if (arr[j] < arr[index]){  
                    index = j;//searching for lowest index  
                }  
            }  
            int smallerNumber = arr[index];   
            arr[index] = arr[i];  
            arr[i] = smallerNumber;  
        }  
    }
}
Please follow us:
error

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*

FACEBOOK
FACEBOOK
YOUTUBE
YOUTUBE