Selection Sort Example Java Program


Definition

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and it has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.

Selection Sort Example Program

public class SelectionSort {
    public static int[] method1(int[] arry){
        for (int i = 0; i < arry.length - 1; i++){
            int count = i;
            for (int j = i + 1; j < arry.length; j++)
                if (arry[j] < arry[count])
                    count = j;
            int smallerNumber = arry[count]; 
            arry[count] = arry[i];
            arry[i] = smallerNumber;
        }
        return arry;
    }
    public static void main(String a[]){
        int[] arry1 = {44,78,56,34,22,99,111,5};
		System.out.println("array before sorting is ");
		for(int i=0;i < arry1.length;i++){
			System.out.println(arry1[i]);
		}	
        int[] arry2 = method1(arry1);
		System.out.println("Array after sorting is");
        for(int i:arry2){
            System.out.print(i);
            System.out.println("");
        }
    }
}

Sample Output

Output is:
Array before sorting is
44
78
56
34
22
99
111
5
Array after sorting is
5
22
34
44
56
78
99
111