Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 36: Write a Java program to perform selection sort.

Selection.java

import java.util.Scanner;

//Class SelectionSort contains the method to perform SelectionSort.
class SelectionSort
{
	//Method to perform selection sort
	public static void selectionSort(int[] arr)
	{
        for(int i=0; i < arr.length-1;i++)
        {
            for(int j=i+1; j < arr.length;j++)
            {
                if(arr[i]>arr[j])
                {
                    int temp=arr[i];
                    arr[i]=arr[j];
                    arr[j]=temp;
                }
            }
        }
	}
}

//Main class 
public class Selection
{
	//Method to take input.
	public static int[] takeInput()
	{
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the number of elements to be included in the array.");
		int size = s.nextInt();
		int arr[] = new int[size];
		
		System.out.println("Enter the element in the array");
		for (int i = 0; i < size; i++)
		{
			arr[i] = s.nextInt();
		}
		return arr;
	}
	
	//Method to print sorted array.
	public static void print(int[] arr)
	{
		for (int i = 0; i < arr.length; i++)
		{
			System.out.print(arr[i]+" ");
		}
	}
	
	//Main method.
	public static void main(String[] args)
	{
		int[] arr = takeInput();
		SelectionSort.selectionSort(arr);
		System.out.println("Sorted Array");
		print(arr);
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.