☞This sorting algorithm is an in place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end.
☞Initially, the sorted part is empty and the unsorted part is the entire list.
☞The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array.
☞This process continues moving unsorted array boundary by one element to the right.
import java.util.*; class SelectionSort{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); System.out.println("Enter the size"); int size=sc.nextInt(); int arr[]=new int[size]; int i,j,min,temp; /*inputting elements in an array*/ System.out.println("Enter the elements"); for(i=0;i<arr.length;i++) arr[i]=sc.nextInt(); /*logic of selection sort*/ for(i=0;i<arr.length-1;i++){ min=i; //setting current element to be minimum /*check the element to be minimum*/ for(j=i+1;j<arr.length;j++){ if(arr[j]<arr[min]) min=j; } /*swap the current element with the next element*/ temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } /*Printing in ascending order*/ System.out.println("The numbers in ascending order are: "); for(i=0;i<arr.length;i++) System.out.print(arr[i]+" "); } }
Enter the size 5 Enter the elements 74 47 84 34 63 The numbers in ascending order are 34 47 63 74 84